2017-02-15 4 views
1

これで、toString()を使って次のように印刷しようとしています:| 5 | 4 | 3 | topLinkedStackを走査してスタック全体を表示する

public String toString(){ 
    String logString = "bottom|"; 
    LLNode<T> node; 
    node = top; 

    while (node != null){ 
     logString = logString + node.getInfo() + "|"; 
     node = node.getLink(); 
     return logString + "top"; 
    } 
    return "Empty Stack"; 
} 

スタック内の0個の要素と1個の要素で動作しますが、3個の要素すべてでテストケースが失敗します。

リンクされたリストの最初の2つのアイテムを取得する方法が失われました。 node = node.getLink();はあなたをリスト内で前方へ移動させます。そのため、スタック内の最後の項目(上端)が3しか表示されず、ループが終了します。どのように後ろに行くのですか?

@Test 
public void test_toString_on_a_stack_with_multiple_elements() { 
    stk1.push(5); stk1.push(4); stk1.push(3); 
    Assert.assertEquals("bottom|5|4|3|top", stk1.toString()); 
} 

expected <bottom|5|4|3|top> actual <bottom|3|top> 
+0

問題が解決した場合は、回答を受け入れることができます。 –

答えて

1

whileループ内ではなく、その後ろにreturnを入れてはいけません。
さらにStringBuilderは非常に便利です。

public String toString(){ 
    LLNode<T> node = top; 
    if (node == null) 
     return "Empty Stack"; 
    StringBuilder toReturn = new StringBuilder("bottom|"); 
    while (node != null){ 
     toReturn.append(node.getInfo()); 
     toReturn.append("|"); 
     node = node.getLink(); 
    } 
    toReturn.append("top"); 
    return toReturn.toString(); 
} 
+0

それはいつも私を得る愚かなエラーです。迅速な応答ありがとう – grumpe

+0

問題ありません。私たちは助けに来ています。 –

0

それは、スタック内の0の要素で動作し、スタック内の1つの要素でしかし私のテストケースは、完全な3つの要素で失敗します。

問題はwhileループ内のreturnステートメントにあります。

while (node != null){ 
    logString = logString + node.getInfo() + "|"; 
    node = node.getLink(); 
    return logString + "top"; // only once the while statement will be executed 
} 

だからこそ、Stackの0または1の要素で動作します。むしろ、そのreturn文をwhileループの外側に置くべきです。

+0

私はいつも愚かな誤りを犯します。 – grumpe

関連する問題