使用泛型类实现Node链表

是msdn中的一个经典例子。

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 使用泛型类实现Node链 { class Program { static void Main(string[] args) { GenericList<int> G = new GenericList<int>(); for (int i = 1; i <= 5; i++) { G.AddHead(5); } //不实现GenericList中的IEnumrator<>,则foreach不可用 foreach (int i in G) { System.Console.Write(i + " "); } System.Console.WriteLine("/nDone"); System.Console.ReadLine(); } } //Node链类 class GenericList<T> { //私有类Node private class Node { public Node(T t) { this.tvalue = t; this.next = null; } private T tvalue; //下一个节点定义在Node类的内部就可以形成链 private Node next; public Node nextNode { get { return this.next; } set { this.next = value; } } public T Tvalue { get { return this.tvalue; } set { this.tvalue = value; } } } //泛型类的构造函数不含<> public GenericList() { this.head = null; } //链的头节点 private Node head; public void AddHead(T tt) { //GenericList<T>.可省略 Node n = new GenericList<T>.Node(tt); //将新加入的节点n设置为头节点,原来的头节点成为next n.nextNode = this.head; this.head = n; } public IEnumerator<T> GetEnumerator() { Node current = this.head; while (current != null) { //yield,在迭代器块中用于向枚举数对象提供值或发出迭代结束信号,返回值必须为T类型 yield return current.Tvalue; current = current.nextNode; } } } }

不实现IEnumerable<>接口,则foreach不可用。foreach每次yield的类型是<>内的类型。

也可以通过IEnumerator<>枚举,如下:

private void Form1_Load(object sender, EventArgs e) { GenericList<string> list = new GenericList<string>(); list.AddHead("zhangsan"); list.AddHead("lisi"); list.AddHead("wanger"); list.AddHead("chensan"); list.AddHead("zhaoliu"); IEnumerator<string> enu = list.GetEnumerator(); bool bln = enu.MoveNext(); while (bln) { Console.WriteLine(enu.Current); bln = enu.MoveNext(); } }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值