2017-04-12 85 views
1

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



} 
+1

究竟是什么问题,在这一点到底在挣扎? –

+0

while(tempNode.next == null) //然后使最后一个节点指向新节点 tempNode.next = newNode; } 我相信push()中的这个循环未设置为通过节点正确迭代。 –

回答

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

感谢您的协助。我解决这个问题的结果与此非常相似,花了很长时间才让我的新手头脑在我身边 –

+0

随时欢迎/接受 –