gpt4 book ai didi

java - 在链表堆栈的push()方法中迭代节点

转载 作者:太空宇宙 更新时间:2023-11-04 11:35:13 25 4
gpt4 key购买 nike

我正在创建一个push()方法,用于将节点添加到链表堆栈中。我无法使用已定义的变量从一个节点迭代和循环到下一个节点。

我尝试了各种循环参数来迭代 .csv 文件,但此时文件中的 5 条记录中仅保留了 1 条记录。 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;
}

关于java - 在链表堆栈的push()方法中迭代节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43378044/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com