在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
用于刪除指定值的節點。你可以根據需要調用這些方法來操作雙向鏈表。