在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
類,用于實現雙向鏈表。這個類包含了Add
、Remove
、Reverse
和Print
方法,分別用于在鏈表末尾添加節點、刪除指定值的節點、反轉鏈表和打印鏈表。在Main
方法中,我們創建了一個DoublyLinkedList
對象,并對其進行了一系列操作,以展示這些高級功能。