我正在创建一个push()方法,用于将节点添加到链接列表堆栈。我无法使用已定义的变量迭代并从一个节点循环到下一个节点。在push()方法中遍历链接列表堆栈中的节点
我已经尝试过各种循环参数来遍历.csv文件,但是在这一点上只保留了文件中五个记录中的一个。 pop方法正在被用来取消堆栈中的顶层节点,所以我的最终结果是打印4个节点。
public class Stack {
Node first;
public Stack() {
//constructor initalizes the empty stack
first = null;
}
public void push(Node newNode) //add the node to the top of the stack
{
//if the stack is empty, make first point to new Node.
if (first == null) {
first = newNode;
return;
} //if the stack is not empty, loop until we get
//to the end of the list
else if (first != null) {
Node tempNode = first;
//loop to advance from one node to the next until
//last node is found
while (tempNode.next == null)
{
//then make the last Node point to the newNode
tempNode.next = newNode;
}
}
}
public Node pop() {
//remove the last node from the top of the stack
{
//if the stack is empty, return null
if(first == null)
{
return null;
}
//handle the case where there is only one node in the stack
else if(first.next == null)
{
System.out.println("Only one node in list");
}
//remove first
return first = first.next;
}
}
public void print()
//print the contents of the entire stack
{
//display the entire stack
//start at the beginning of linkedList
Node tempDisplay = first;
while (tempDisplay != null) //executes until we don't find end of list.
{
tempDisplay.displayNode();
tempDisplay = tempDisplay.next; // move to next Node
}
System.out.println();
}
}
究竟是什么问题,在这一点到底在挣扎? –
while(tempNode.next == null) //然后使最后一个节点指向新节点 tempNode.next = newNode; } 我相信push()中的这个循环未设置为通过节点正确迭代。 –