以下是一个使用泛型节点类和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#泛型实现单向链表内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论