2016-04-06 12 views
0

Stackを最初から作成していて、toString()メソッドを作成するのが難しいです。私はスタックの残りの部分を完成させました。私は割り当てであるので、最初から作成しています。もし私が間違ってやっていることのヒントを得ることができれば、それは非常に役に立つでしょう、ありがとう!!toStringを最初から作成する?

public class MyStack<Type> { 
    private Node top; 
    private int size; 

    private class Node{ 
     private Node next; 
     private Type current; 

     public Node() { 
      next = null; 
      current = null; 
     } 
    } 

    public void push(Type item) { 
     Node old = top; 
     top = new Node(); 

     top.current = item; 
     top.next = old; 

     size++; 

    } 

    public Type pop() { 
     Type type = null; 
     if(top != null) { 
      type = top.current; 
      top = top.next; 
      size--; 
     } 

     return type; 
    } 

    public Type peek(){ 
     return top.current; 
    } 

    public int size() { 
     return size; 
    } 
    public boolean isEmpty(){ 
     boolean result = false; 
     if(size > 0) { 
      result = false; 
     } else{ 
      result = true; 
     } 
     return result; 
    } 

    public String toString() { // this is where I'm having issues. 
     String result = "["; 
     if(top != null) { 
      while(top.next != null) { 
       result = result + top.current; 
      } 

     } 

     result = result + "]"; 
     return result; 
    } 
} 
+0

*私は私が間違ってやっているのヒントを得ることができた場合*あなたは問題が何であるかを教えていませんでした。 – Guy

+0

@Guy申し訳ありませんので、基本的に私のtoStringは、私がそれを呼び出しても何も印刷しない、またはpushメソッドを使用しています。私はプッシュとポップが正しく動作していることを知っていますが、toStringは何も出力しません。whileループには入っていません。 – thatsnifty

+0

実際の問題で問題を述べる方が良いです。 – Pullie

答えて

0

は、スタック、リスト、キュー、ツリーまたはあなたが実装する任意の他のコレクションを横断するtopを使用しないでください。あなたがこのコレクションの始まりを参照してくれるからです。代わりに一時変数を作成してそれをトラバースします。

//toString in MyStack class 
public String toString(){ 
    String s = ""; 
    Node temp = top; 
    while(temp != null){ 
     s+= temp + " "; 
     temp = temp.getNext(); 
    } 
    return s; 
} 

//toString in Node class 
public String toString(){ 
    return current +" 
} 

public Node getNext(){ 
    return next; 
} 
+0

私はこの解決策を使用するとき、私はこの行でプライベートノードnextを例外にします。 – thatsnifty

+0

@thatsnifty 'Node'クラスに' getNext() 'メソッドを追加します。 – Yoda

+0

@Yoda私は今、 'temp = temp.getNext()'という行でnullpointerexceptionを取得しています。 – thatsnifty

関連する問題