温馨提示×

C#双向链表的插入与删除操作

c#
小樊
83
2024-08-29 04:46:58
栏目: 编程语言

在C#中,双向链表是一种数据结构,其中每个节点都有两个指针,一个指向前一个节点,另一个指向后一个节点

首先,我们需要定义一个双向链表节点类:

public class DoublyLinkedListNode<T>
{
    public T Value;
    public DoublyLinkedListNode<T> Previous;
    public DoublyLinkedListNode<T> Next;

    public DoublyLinkedListNode(T value)
    {
        Value = value;
        Previous = null;
        Next = null;
    }
}

接下来,我们可以实现插入和删除操作:

public class DoublyLinkedList<T>
{
    public DoublyLinkedListNode<T> Head;
    public DoublyLinkedListNode<T> Tail;

    // 在链表头部插入节点
    public void InsertAtHead(T value)
    {
        var newNode = new DoublyLinkedListNode<T>(value);
        if (Head == null)
        {
            Head = newNode;
            Tail = newNode;
        }
        else
        {
            newNode.Next = Head;
            Head.Previous = newNode;
            Head = newNode;
        }
    }

    // 在链表尾部插入节点
    public void InsertAtTail(T value)
    {
        var newNode = new DoublyLinkedListNode<T>(value);
        if (Tail == null)
        {
            Head = newNode;
            Tail = newNode;
        }
        else
        {
            newNode.Previous = Tail;
            Tail.Next = newNode;
            Tail = newNode;
        }
    }

    // 删除指定值的节点
    public void Delete(T value)
    {
        var currentNode = Head;
        while (currentNode != null)
        {
            if (currentNode.Value.Equals(value))
            {
                if (currentNode.Previous != null)
                    currentNode.Previous.Next = currentNode.Next;
                else
                    Head = currentNode.Next;

                if (currentNode.Next != null)
                    currentNode.Next.Previous = currentNode.Previous;
                else
                    Tail = currentNode.Previous;
            }
            currentNode = currentNode.Next;
        }
    }
}

这里我们实现了三个方法:InsertAtHead用于在链表头部插入节点,InsertAtTail用于在链表尾部插入节点,Delete用于删除指定值的节点。你可以根据需要调用这些方法来操作双向链表。

0