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

时间:2017-04-12 19:27:01

标签: java

我正在创建一个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();
    }



}

1 个答案:

答案 0 :(得分:0)

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;
}