C#使用泛型方法设计实现单向链表详解
作者:wenchm
这篇文章主要为大家详细介绍了C#如何使用泛型方法设计实现一个单向链表,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
以下是一个使用泛型节点类和LinkedList<T>类的示例,其中包含Insert方法用于插入新节点,并在插入后更新当前节点。同时,GetCurrentValue方法用于获取当前节点的值,并将其转换为int类型。
1.先设计一个泛型节点类Node<T>
/// <summary>
/// 定义泛型节点类
/// </summary>
public class Node<T>(T data)
{
public T Data { get; set; } = data;
public Node<T>? Next { get; set; } = null;
}
2.在设计一个泛型链表类LinkedList<T>
定义一个包含Insert和GetCurrentValue方法的LinkedList<T>类:
/// <summary>
/// 定义泛型链表类LinkedList<T>
/// </summary>
public class LinkedList<T> where T : struct
{
private Node<T>? head;
private Node<T>? current;
public void Insert(T value)
{
var newNode = new Node<T>(value);
if (head == null)
{
head = newNode;
current = newNode;
}
else
{
Node<T> temp = head;
while (temp.Next != null)
{
temp = temp.Next;
}
temp.Next = newNode;
current = newNode;
}
}
// 定义GetCurrentValue()方法,获取当前节点
public int GetCurrentValue()
{
if (head == null)
{
throw new InvalidOperationException("The linked list is empty.");
}
return LinkedList<T>.ConvertToInt(head.Data);
}
// 把<T>转换为int类型
private static int ConvertToInt(T value)
{
return checked((int)(object)value);
}
}
使用类似的方法在LinkedList<T>类中添加其他方法。
3.创建一个LinkedList<int>类的实例
创建一个LinkedList<int>类的实例,插入一些节点,并显示当前节点的值:
var linkedList = new LinkedList<int>(); linkedList.Insert(5); linkedList.Insert(10); linkedList.Insert(15); Console.WriteLine(linkedList.GetCurrentValue()); // 输出:15
这个示例假设类型T可以转换为int。在实际应用中,请确保T的类型符合您的需求。
到此这篇关于C#使用泛型方法设计实现单向链表详解的文章就介绍到这了,更多相关C#泛型实现单向链表内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
