双向链表是一种数据结构,每个节点包含两个指针,一个指向前一个节点,一个指向后一个节点。在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
类中实现其他方法,如添加、删除、搜索等。