如何从双向链表中删除节点?

时间:2014-02-23 00:21:14

标签: c# algorithm doubly-linked-list

我需要创建一个从双向链表中删除给定节点(名为“Jack”的节点)的方法。

这是我的代码:

链表类:

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个节点,我想删除“Jack”节点。

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(); 

    }

2 个答案:

答案 0 :(得分:1)

  1. 找到节点n
    1. 如果n.Next不是null,请将n.Next.Prev设为n.Prev
    2. 如果n.Prev不是null,请将n.Prev.Next设为n.Next
    3. 如果n == head,请将head设置为n.Next
  2. 基本上,您找到要删除的节点,并使其左侧的节点指向其右侧的节点,反之亦然。

    要查找节点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属性为空 - 您可以将其读作:“没有节点出现在第一个节点之前,并且没有节点位于最后一个节点“。

    之后

答案 1 :(得分: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;
        } 
     }
}