在C#中,可以通过以下步骤实现双向链表的逆序:
public class Node
{
public int Data { get; set; }
public Node Prev { get; set; }
public Node Next { get; set; }
public Node(int data)
{
Data = data;
Prev = null;
Next = null;
}
}
public class DoublyLinkedList
{
public Node Head { get; set; }
public Node Tail { get; set; }
public DoublyLinkedList()
{
Head = null;
Tail = null;
}
// 添加节点的方法
public void AddNode(int data)
{
Node newNode = new Node(data);
if (Head == null)
{
Head = newNode;
Tail = newNode;
}
else
{
Tail.Next = newNode;
newNode.Prev = Tail;
Tail = newNode;
}
}
// 逆序双向链表的方法
public void Reverse()
{
Node current = Head;
Node temp = null;
while (current != null)
{
temp = current.Prev;
current.Prev = current.Next;
current.Next = temp;
current = current.Prev;
}
if (temp != null)
{
Head = temp.Prev;
}
}
// 打印链表的方法
public void PrintList()
{
Node current = Head;
while (current != null)
{
Console.Write(current.Data + " ");
current = current.Next;
}
Console.WriteLine();
}
}
class Program
{
static void Main(string[] args)
{
DoublyLinkedList list = new DoublyLinkedList();
list.AddNode(1);
list.AddNode(2);
list.AddNode(3);
list.AddNode(4);
list.AddNode(5);
Console.WriteLine("Original list:");
list.PrintList();
list.Reverse();
Console.WriteLine("Reversed list:");
list.PrintList();
}
}
运行代码后,可以看到原始双向链表和逆序后的双向链表的输出结果。