雙向鏈表是一種數據結構,每個節點包含兩個指針,一個指向前一個節點,一個指向后一個節點。在C#中,可以使用以下方法來遍歷雙向鏈表:
using System;
public class Node
{
public int data;
public Node prev;
public Node next;
public Node(int d)
{
data = d;
prev = null;
next = null;
}
}
public class DoublyLinkedList
{
public Node head;
public void TraverseForward()
{
Node current = head;
while (current != null)
{
Console.Write(current.data + " ");
current = current.next;
}
Console.WriteLine();
}
public void TraverseBackward()
{
Node current = head;
while (current.next != null)
{
current = current.next;
}
while (current != null)
{
Console.Write(current.data + " ");
current = current.prev;
}
Console.WriteLine();
}
// Other methods to add, delete, search, etc.
}
在上面的代碼中,我們定義了一個Node
類來表示雙向鏈表的節點,其中包含數據和前后指針。然后定義了一個DoublyLinkedList
類來管理雙向鏈表,包含了兩個方法TraverseForward
和TraverseBackward
來遍歷鏈表的前向和后向方向。您可以根據需要在DoublyLinkedList
類中實現其他方法,如添加、刪除、搜索等。