2014-02-23 64 views
0

我需要創建一個方法來從雙向鏈表中刪除給定的節點(稱爲「傑克」的節點)。如何從雙向鏈表中刪除節點?

這裏是我的代碼:

鏈表類:

class DoublyLinkedList 
{ 
    public Node head, current; 

    public void AddNode(object n) // add a new node 
    { 
     if (head == null) 
     { 
      head = new Node(n); //head is pointed to the 1st node in list 
      current = head; 
     } 
     else 
     { 
      while (current.next != null) 
      { 
       current = current.next; 
      } 

      current.next = new Node(n, current); //current is pointed to the newly added node 
     } 
    } 

    public void RemoveNode(object n) 
    { 

    } 

    public String PrintNode() // print nodes 
    { 
     String Output = ""; 

     Node printNode = head; 
     if (printNode != null) 
     { 
      while (printNode != null) 
      { 
       Output += printNode.data.ToString() + "\r\n"; 
       printNode = printNode.next; 
      } 
     } 
     else 
     { 
      Output += "No items in Doubly Linked List"; 
     } 
     return Output; 
    } 

} 

執行按鈕代碼: 我已經添加了3個節點,你可以看到,我想刪除「傑克」節點。

private void btnExecute_Click(object sender, EventArgs e) 
    { 
     DoublyLinkedList dll = new DoublyLinkedList(); 
     //add new nodes 
     dll.AddNode("Tom"); 
     dll.AddNode("Jack"); 
     dll.AddNode("Mary"); 
     //print nodes 
     txtOutput.Text = dll.PrintNode(); 

    } 
+0

@deviantfan問題是我不知道如何創建一個方法,刪除節點。 – Maattt

+0

@nintendojunkie我沒有嘗試過任何東西,因爲我不知道該怎麼做,我對此很新。 – Maattt

+0

無論誰投票結束這個問題,因爲「缺乏足夠的信息來診斷問題。」 - 顯然,有足夠的信息來診斷問題。我不明白爲什麼應該關閉。 – dcastro

回答

1
  1. 找到節點n
    1. 如果n.Nextnull,設置n.Next.Prevn.Prev
    2. 如果n.Prevnull,設置n.Prev.Nextn.Next
    3. 如果n == head,設置headn.Next

基本上,你找到你要刪除的節點,使節點到其左指向節點其右,反之亦然。

爲了找到節點n,你可以做這樣的事情:

public bool Remove(object value) 
{ 
    Node current = head; 

    while(current != null && current.Data != value) 
     current = current.Next; 

    //value was not found, return false 
    if(current == null) 
     return false; 

    //... 
} 

注:這些算法通常涉及到兩個變量。您必須始終確保第一個節點的Prev屬性和最後一個節點的Next屬性爲空 - 您可以將其讀爲:「沒有節點出現在第一個節點之前,並且沒有節點出現在最後一個節點之後」。

+0

這對我有意義,但如何找到節點? – Maattt

+0

@SpiritualEvolution作爲一個便箋,你會想讓你的'head'和'current'字段是私人的,也許考慮把你的列表作爲一個練習來使用。 – dcastro

+0

非常感謝。你的回答非常簡單,我現在很瞭解它。至於通用清單,這是我的下一步。再次感謝 – Maattt

0

你的代碼應該包含Previous指針,使它成爲雙向鏈表。

public void RemoveNode(object n) 
{ 
    Node lcurrent = head; 

    while(lcurrent!=null && lcurrent.Data!=n) //assuming data is an object 
    { 
     lcurrent = lcurrent.Next; 
    } 
    if(lcurrent != null) 
    { 
     if(lcurrent==current) current = current.Previous; //update current 
     if(lcurrent==head) 
     { 
      head = lcurrent.Next; 
     } 
     else 
     { 
      lcurrent.Previous.Next = lcurrent.Next; 
      lcurrent.Next.Previous = lcurrent.Previous; 
      lcurrent.Next = null; 
      lcurrent.Previous = null; 
     } 
    } 
} 
+0

您的算法存在一些問題。 'head.Previous!= null'將始終爲假,因爲沒有節點出現在頭部之前。另外,我敢肯定,'n'將是節點的價值,而不是節點本身,所以演員陣容將失敗。 – dcastro

+0

@dcastro你是對的..我的壞..我不知何故在我心中留下了循環鏈表 – Dexters