2015-09-18 30 views
0

我沒有成功從鏈表中刪除特定的項目,方法是 - 公共無效removeFromList(字符串itemtoremove,LinkedList列表)。我如何編寫一個從鏈表中刪除特定對象的方法?

我該如何編寫從鏈表中刪除特定項目的方法?

我的代碼是:

public class Node 
{ 

    public Node next; //saves the adress 
    public Person data; //saves the person 

} 

public class LinkedList 
{ 
    private Node head; //starts from the begging 

    public void AddFirst(Person data) 
    { 

     Node toAdd = new Node(); 
     toAdd.data = data; // in data he saves the object 
     toAdd.next = head; 

     head = toAdd; 

    } 

    public void removeFromList(string itemtoremove, LinkedList List) // 
    { 

     Node current = head; 
     Node current1 = current.next; 
     while (current1 != null) 
     { 

      if (current1.data.instrument == itemtoremove) 
      ??? 

     } 

    } 

} 
+0

找到元素以前你正在尋找的一個,然後設置'next'這個元素來'itemtoremove.next' – thumbmunkeys

+0

有你滾你自己的實現鏈表的原因是什麼? –

回答

1

你的方法已經有一個問題之前,你甚至實現算法。您正在跳過頭節點。您也不需要將鏈接列表作爲參數傳遞給實例方法。

public void removeFromList(string itemtoremove) 
{ 
    Node previousNode = null; 
    Node current = head; 
    while (current != null) //starting with current1 would ignore the head node 
    { 
     // we found a match 
     if (current.data.instrument == itemtoremove){ 
      // head node is treated slightly differently 
      if(current == head){ 
       // set the next node to the new head 
       head = current.next; 

       // set to null so GC can clean it up 
       current = null; 
       return; 
      } 
      else { 
       //update the previous node's link 
       previousNode.next = current.next; 
       current = null; 
       return; 
      } 
     } 

     // move on to the next 
     previousNode = current; 
     current = current.next; 
    } 

} 
相關問題