在C#中,要創建一個雙向鏈表,首先需要定義一個表示鏈表節點的類,其中包含指向前一個和后一個節點的引用
public class Node<T>
{
public T Data { get; set; }
public Node<T> Previous { get; set; }
public Node<T> Next { get; set; }
public Node(T data)
{
Data = data;
Previous = null;
Next = null;
}
}
public class DoublyLinkedList<T>
{
private Node<T> _head;
private Node<T> _tail;
public DoublyLinkedList()
{
_head = null;
_tail = null;
}
// 在鏈表末尾添加新節點
public void Add(T data)
{
var newNode = new Node<T>(data);
if (_head == null)
{
_head = newNode;
_tail = newNode;
}
else
{
newNode.Previous = _tail;
_tail.Next = newNode;
_tail = newNode;
}
}
// 從鏈表中刪除節點
public bool Remove(T data)
{
var current = _head;
while (current != null)
{
if (current.Data.Equals(data))
{
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;
return true;
}
current = current.Next;
}
return false;
}
// 打印鏈表中的所有元素
public void Print()
{
var current = _head;
while (current != null)
{
Console.Write(current.Data + " ");
current = current.Next;
}
Console.WriteLine();
}
}
以下是如何使用這個雙向鏈表類的示例:
class Program
{
static void Main(string[] args)
{
var list = new DoublyLinkedList<int>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Print(); // 輸出: 1 2 3
list.Remove(2);
list.Print(); // 輸出: 1 3
}
}
這個實現提供了基本的雙向鏈表功能,包括添加、刪除和打印鏈表中的元素。你可以根據需要擴展此實現,例如添加更多的遍歷方法或者實現鏈表的其他操作。