2011-12-01 57 views
0

StackOverflowers。鏈接列表輸出沒有正確生成

我對這個網站相當陌生,並認爲明智的來到這裏尋求幫助,解決一個特殊問題,包括從鏈表打印正確的輸出。 這個想法是採用一個程序,使用一個數組來生成一個列表並將其轉換成一個鏈表,同時達到相同的結果。現在,我已經持續了好幾個小時,即使達到了輸出實際打印的地步(最後),也沒有獲得所需的結果。

需要的結果:
注意:該結果產生與使用陣列

詞語:該計數:2
字:當然數:2
詞語:檢數:1個
詞語:計數:7
詞語:施工數:1個
詞語:9
字:計數算法數:4
詞語:和計數:9


結果我獲得:
注:信仰數:2
字轉換陣列的方法爲鏈表

字時,這個結果產生:我的計數:2
Word:of count:2
Word:best count:2
Word:伯爵:2
字:數:2
字:是計數:2
字:事實數:2
詞:計:2

我不知道是什麼原因,這是案件和我似乎無法跟蹤它。我嘗試閱讀我的筆記和搜索,但無濟於事。我不確定它是否與setNext(...)[Node類的一部分]有關,或者我正在調用incrementCount()方法[Word類的一部分]。我不相信setNext(...)甚至有目的,但只是代碼的一部分,在這一點上什麼也不做。

我希望我的交付不會偏離軌道,並且可以爲我的嘗試提供解決方案。我知道我已經達到了我的極限,因爲我無法想到與此有關的其他任何事情。

期待您的建議。

謝謝。 T3:

T3。

private Node top; 

public WordList() 
{ 
    top = null; 
} 

    // This method adds words to the linked list. 
public void addWord(String w) 
{  
    Word word = new Word(w); 
    top = new Node(word,top); 

     // Checks to see if a particular word is present more than once. 
     // If the particular word is encountered more than once, it 
     // increments the word count for that particular word, else 
     // a new node is created to store another word. The word check 
     // process is repeated once more. 
     // Note: getWord() is part of the Node class that attempts to retrieve 
     // a word that is held in a particular node. 
     // matchesWord(...) determines whether a particular word (string) has been 
     // encountered. If result is true, the number of times 
     // the word is encountered should be incremented. 
    if(top.getWord().matchesWord(w)) 
    { 
     top.getWord().incrementCount(); 
    } 
    else 
    { 
     Word newWord = new Word (w); 
     Node newNode = new Node(newWord, top);  
     //top = newNode; 
     top.setNext(newNode); 
    } 
} // end addWord 

    // This method prints out the linked list. 
public void printList() 
{ 
    Node currentNode; 

    currentNode = top.getNext(); 
    while(currentNode != null) 
    { 
     System.out.println(currentNode.getWord()); 
     currentNode = currentNode.getNext(); 
    } 
} 

回答

1

有幾個問題,我可以看到立竿見影:

  • 除非getWord()方法做了比較奇怪的,它只會如果第一個字的匹配外新增加的數添加單詞
  • 您正在將新的Node添加到列表的頭部,而不管是否存在匹配 - 將第一個問題結果與您的計數相加,結果爲2
  • printList(),則需要在top開始不top.getNext()
+0

屏幕取詞()只返回一個儲存在節點A字對象。就是這樣。我試圖修復printList()方法,但仍然無法解決錯誤。 – TicklyTurtle

+0

您是否理解我說過每次調用addWord()時總是添加一個'Node'?拿出這條線,並嘗試迭代你的名單來尋找匹配,而不是僅僅檢查頂部的什麼' – millhouse

+0

我很感謝你的幫助,但是看到我沒有進步,我只會向你表示感謝,並且保持原樣。 :-)我盡我所能。很榮幸能收到你的回答。 – TicklyTurtle