繁体   English   中英

在push()方法中迭代节点以查找链表

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM