2017-04-12 1 views
1

リンクリストスタックにノードを追加するためのpush()メソッドを作成しています。私はすでに定義された変数を使って、あるノードから次のノードへと反復してループすることができません。リンクリストスタックの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(); 
    } 



} 
+1

あなたが正確にその時点で正確に何の問題があるが、苦労していますか? –

+0

while(tempNode.next == null) { // newNodeの最後のノードポイントを指定します tempNode.next = newNode; } push()内のこのループは、ノードを介して正しく反復するように設定されていないと考えています。 –

答えて

0

あなたwhileループ内のコードは、(tempNodeの子として)リンクリストの末尾にnewNodeを付けます。これは正しいですが、ループ内で実行すべきではありません。これを修正するには、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

自由にupvote/acceptに気軽に –

関連する問題