阅读量:2
实现双向链表可以借助 C# 中的泛型来实现。以下是一个简单的双向链表的示例代码:
using System;
public class Node<T>
{
public T Data { get; set; }
public Node Next { get; set; }
public Node Prev { get; set; }
public Node(T data)
{
Data = data;
Next = null;
Prev = null;
}
}
public class LinkedList<T>
{
private Node head;
private Node tail;
public void Add(T data)
{
Node newNode = new Node(data);
if (head == null)
{
head = newNode;
tail = newNode;
}
else
{
tail.Next = newNode;
newNode.Prev = tail;
tail = newNode;
}
}
public void Print()
{
Node current = head;
while (current != null)
{
Console.Write(current.Data + " ");
current = current.Next;
}
Console.WriteLine();
}
}
class Program
{
static void Main()
{
LinkedList<int> list = new LinkedList<int>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Print();
}
}
在这个示例中,我们定义了一个 Node 类表示链表中的节点,包含数据和指向前一个节点和后一个节点的引用。然后定义了一个 LinkedList 类表示双向链表,包含添加节点和打印链表的方法。
你可以根据需要修改或扩展这个代码来实现更多功能。希望这个示例能够帮助到你实现双向链表。
以上就是关于“如何利用C#泛型实现双向链表”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm