2014-11-21 49 views
-1

嗨,大家好,我正在嘗試刪除具有特定名稱的節點。但顯然不會刪除節點,它只是打印出所有內容。包含該名稱的節點不會被刪除。我寫了鏈接列表,除了刪除具有特定名稱的節點外,其他所有的東西都可以工作。下面是我刪除特定名稱的方法:刪除方法不會刪除具有特定名稱的節點

public void remove(String name) 
{ 
    if(!this.isEmpty()) 
    { 
     LinkedList current = first; 
     //LinkedList prev = null; 
     while(current!=null) 
     { 
      //prev = current; 
      if(current.name.equals(name)) 
      { 
       current = current.getNext(); 
       count--; 
       break; 
      } 
      current=current.getNext(); 
     } 
    } 
    else 
    { 
     System.out.println("Cannot search an empty list"); 
    } 
} 

主要方法:

public static void main(String[] args) { 
    // TODO Auto-generated method stub 
    Link a = new Link(); 
    a.addEnd("Tom"); //adds at the end of list 
    a.addEnd("Joe"); 
    a.addEnd("Gary"); 
    a.add("Kim"); //adds at the beginning of the list 
    a.addIndex("Nene", 1); //adds to an index position. 
    a.remove("Kim"); //calls the method to remove the name kim but doesn't delete it.still displays kim on the console. 
     a.display(); 
} 
} 
+0

你需要上一個節點來刪除當前節點。或者,您可以將所有數據從下一個節點移動到當前節點,但如果它是鏈接列表中的最後一個節點,則無法工作。 – mostruash 2014-11-21 00:19:36

+0

代碼中沒有任何一行試圖刪除一個節點,這就是問題所在。當名稱匹配和名稱不匹配時,可以執行'current = current.getNext()'。您應該更改鏈接列表中的至少一個鏈接。 – 2014-11-21 00:56:14

回答

1

我覺得一個非常小的調整,將得到這個工作。我在做,你擴展的假設內置Java的LinkedList:

在您的條件:

if(!this.isEmpty()) 
{ 
    LinkedList current = first; 
    //LinkedList prev = null; 
    while(current!=null) 
    { 
     //prev = current; 
     if(current.name.equals(name)) 
     { 
      // Right here you need to do a this.remove(current.getId) 
      current = current.getNext(); 
      count--; 
      break; 
     } 
     current=current.getNext(); 
    } 
} 

你遞減計數,但你實際上沒有從刪除元素列表。建立在LinkedList中的Java有一個ID去除方法:LinkedList.remove。既然你已經獲得了與名稱匹配的元素,那麼你應該能夠將該元素的ID的索引傳遞給remove方法。

如果您沒有將此作爲現有方法的擴展,那麼我會建議您使用前瞻性的。瞭解你的現在和未來。這樣你就可以遵循這個邏輯(赦免我的僞代碼):

If next matches, do next.getNext() 
If next.getNext() returns null, 
    then pop the last value off the list (current.setNext(null)) 
Else 
    do current.setNext(next.getNext())