c# 自定义泛型链表类的详解
程序员文章站
2023-12-19 10:13:22
(1)自定义泛型链表类。复制代码 代码如下:public class genericlist {  ...
(1)自定义泛型链表类。
public class genericlist<t>
{
private class node
{
//当前节点值
private t data;
public t data
{
get { return data; }
set { data = value; }
}
//节点的下一个节点
private node next;
public node next
{
get { return next; }
set { next = value; }
}
//节点的上一个节点
private node last;
public node last
{
get { return last; }
set { last = value; }
}
public node(t t)
{
data = t;
next = null;
}
}
private node firstnode;
private node lastnode;
public void addnode(t t)
{
node node = new node(t);
node.last = lastnode;
if (lastnode != null)
lastnode.next = node;
lastnode = node;
if (firstnode == null)
{
firstnode = node;
}
}
//要在自定义泛型集合上迭代
//必须实现该接口
public ienumerator<t> getenumerator()
{
node current = firstnode;
while (current != null)
{
//yield return表达式以枚举对象返回
yield return current.data;
current = current.next;
}
}
}
(2)自定义泛型链表类调用。
class genericlisttesttwo
{
static void main()
{
// 类型参数为int
genericlist<int> list = new genericlist<int>();
for (int a = 0; a < 5; a++)
{
list.addnode(a);
}
foreach (int i in list)
{
system.console.writeline(i);
}
//类型参数为string
genericlist<string> strlist = new genericlist<string>();
strlist.addnode("first node");
strlist.addnode("second node");
foreach(string s in strlist)
{
system.console.writeline(s);
}
console.read();
}
}
输出如下:
复制代码 代码如下:
public class genericlist<t>
{
private class node
{
//当前节点值
private t data;
public t data
{
get { return data; }
set { data = value; }
}
//节点的下一个节点
private node next;
public node next
{
get { return next; }
set { next = value; }
}
//节点的上一个节点
private node last;
public node last
{
get { return last; }
set { last = value; }
}
public node(t t)
{
data = t;
next = null;
}
}
private node firstnode;
private node lastnode;
public void addnode(t t)
{
node node = new node(t);
node.last = lastnode;
if (lastnode != null)
lastnode.next = node;
lastnode = node;
if (firstnode == null)
{
firstnode = node;
}
}
//要在自定义泛型集合上迭代
//必须实现该接口
public ienumerator<t> getenumerator()
{
node current = firstnode;
while (current != null)
{
//yield return表达式以枚举对象返回
yield return current.data;
current = current.next;
}
}
}
(2)自定义泛型链表类调用。
复制代码 代码如下:
class genericlisttesttwo
{
static void main()
{
// 类型参数为int
genericlist<int> list = new genericlist<int>();
for (int a = 0; a < 5; a++)
{
list.addnode(a);
}
foreach (int i in list)
{
system.console.writeline(i);
}
//类型参数为string
genericlist<string> strlist = new genericlist<string>();
strlist.addnode("first node");
strlist.addnode("second node");
foreach(string s in strlist)
{
system.console.writeline(s);
}
console.read();
}
}
输出如下: