温馨提示×

利用C#实现双向链表的高级功能

c#
小樊
82
2024-08-29 04:55:10
栏目: 编程语言

在C#中,可以使用类来实现双向链表的高级功能

using System;

public class Node
{
    public int Value;
    public Node Previous;
    public Node Next;

    public Node(int value)
    {
        Value = value;
        Previous = null;
        Next = null;
    }
}

public class DoublyLinkedList
{
    private Node _head;
    private Node _tail;

    public DoublyLinkedList()
    {
        _head = null;
        _tail = null;
    }

    // 在链表末尾添加节点
    public void Add(int value)
    {
        Node newNode = new Node(value);

        if (_head == null)
        {
            _head = newNode;
            _tail = newNode;
        }
        else
        {
            newNode.Previous = _tail;
            _tail.Next = newNode;
            _tail = newNode;
        }
    }

    // 删除指定值的节点
    public void Remove(int value)
    {
        Node current = _head;

        while (current != null)
        {
            if (current.Value == value)
            {
                if (current.Previous != null)
                {
                    current.Previous.Next = current.Next;
                }
                else
                {
                    _head = current.Next;
                }

                if (current.Next != null)
                {
                    current.Next.Previous = current.Previous;
                }
                else
                {
                    _tail = current.Previous;
                }
            }

            current = current.Next;
        }
    }

    // 反转链表
    public void Reverse()
    {
        Node current = _head;
        Node temp = null;

        while (current != null)
        {
            temp = current.Previous;
            current.Previous = current.Next;
            current.Next = temp;
            current = current.Previous;
        }

        if (temp != null)
        {
            _head = temp.Previous;
        }
    }

    // 打印链表
    public void Print()
    {
        Node current = _head;

        while (current != null)
        {
            Console.Write(current.Value + " ");
            current = current.Next;
        }

        Console.WriteLine();
    }
}

class Program
{
    static void Main(string[] args)
    {
        DoublyLinkedList list = new DoublyLinkedList();

        list.Add(1);
        list.Add(2);
        list.Add(3);
        list.Add(4);
        list.Add(5);

        Console.WriteLine("Original list:");
        list.Print();

        list.Remove(3);
        Console.WriteLine("List after removing 3:");
        list.Print();

        list.Reverse();
        Console.WriteLine("Reversed list:");
        list.Print();
    }
}

这个示例中,我们创建了一个DoublyLinkedList类,用于实现双向链表。这个类包含了AddRemoveReversePrint方法,分别用于在链表末尾添加节点、删除指定值的节点、反转链表和打印链表。在Main方法中,我们创建了一个DoublyLinkedList对象,并对其进行了一系列操作,以展示这些高级功能。

0