2015-07-19 163 views
0

我要編寫一個菜單驅動的程序,它可以接受單詞及其含義,或以字典順序(即在字典中)顯示單詞列表。 我必須寫的一種方法是刪除方法。該分配基於鏈表的基本屬性。我們實際上並沒有使用鏈表類。 這是我到目前爲止有:刪除鏈接列表中的節點java

public String delete(String a) { 
    boolean found = false; 
    WordNode aux = list; 
    WordNode back = null; 
    String deleted = ""; 

    while (aux != null && !found) { 

     if (a.equalsIgnoreCase(aux.getAll().getWord())) { 
      deleted = deleted + aux.getAll().getWord(); 

      back = aux.next; 

      aux = null; 

      found = true; 
     } else { 

      back = aux; 
      aux = aux.next; 

     } 

    } 
    return deleted; 
} 

但每當我把我的主類的刪除方法,然後打電話給我的toString,該列表是完整的。被刪除的單詞仍然在列表中。

+1

我沒有看到任何實際刪除回事! –

+0

你想從列表中刪除字符串a嗎?如果是這樣,那麼刪除用的是什麼?正如Robert Moskal所指出的那樣,刪除在哪裏? – c0der

+1

變量'found'不是必需的,並且是多餘的。 –

回答

0

所有你需要做的就是改變行(這是第12行,我認爲)

back = aux.next; 

if (back == null) 
    list.next = aux.next; 
else 
    back.next = aux.next; 
1

也許這樣?

public String delete(String a) { 
    WordNode aux = list; 
    WordNode back = null;   

    while (aux != null) { 

     if (a.equalsIgnoreCase(aux.getAll().getWord())) { 

     if (back != null) { 
      //change the pointer from the previous node to the one after the deleted one 
      back.next = aux.next; 
     } else { 
      //first node was found, so modify list to point his successor as the new head 
      list = aux.next; 
     } 
     return a; 
     } else { 
     back = aux; 
     aux = aux.next; 
     } 

    } 
    return ""; //no node was found 
} 

這應該符合您的合同,但我會考慮傳遞列表作爲參數並返回指向頭部的指針。