[英]Iterating through nodes in a push() method for a linked list stack
我正在創建一個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
循環中的代碼將newNode
附加到鏈表的末尾(作為tempNode
)。 這是正確的,但不應該在循環內完成。 要解決此問題,請將賦值tempNode.next = newNode
移出循環。
現在你需要確保,當這個賦值發生時, tempNode
實際上是最后一個節點。 為此,請使用以下循環:
while (tempNode.next != null) {
tempNode = tempNode.next;
}
總的來說,這可能是結果:
public void push(Node newNode) {
if (first == null) {
first = newNode;
return;
}
Node tempNode = first;
while (tempNode.next != null) {
tempNode = tempNode.next;
}
tempNode.next = newNode;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.