溫馨提示×

利用C#實(shí)現(xiàn)雙向鏈表的高級功能

c#
小樊
82
2024-08-29 04:55:10
欄目: 編程語言

在C#中,可以使用類來實(shí)現(xiàn)雙向鏈表的高級功能

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;
    }

    // 在鏈表末尾添加節(jié)點(diǎn)
    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;
        }
    }

    // 刪除指定值的節(jié)點(diǎn)
    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;
        }
    }

    // 反轉(zhuǎn)鏈表
    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();
    }
}

這個(gè)示例中,我們創(chuàng)建了一個(gè)DoublyLinkedList類,用于實(shí)現(xiàn)雙向鏈表。這個(gè)類包含了AddRemove、ReversePrint方法,分別用于在鏈表末尾添加節(jié)點(diǎn)、刪除指定值的節(jié)點(diǎn)、反轉(zhuǎn)鏈表和打印鏈表。在Main方法中,我們創(chuàng)建了一個(gè)DoublyLinkedList對象,并對其進(jìn)行了一系列操作,以展示這些高級功能。

0