繁体   English   中英

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

[英]How to remove a node from a doubly linked list?

我需要创建一种方法来从双向链表中删除给定的节点(称为“杰克”的节点)。

这是我的代码:

链表类:

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

    }
  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

基本上,您会找到要删除的节点,并使该节点的左侧指向其右侧的节点,反之亦然。

要找到节点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属性为空-您可以将其读取为:“第一个节点之前没有节点,最后一个节点之后没有节点”。

您的代码应包含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;
        } 
     }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM