泛型---泛型链表
/* ----泛型--- 性能:泛型类型在JIT时不在进行装箱拆箱 类型安全性:定义是什么类型就必须放入什么类型 二进制代码重用:可以在.NET中其他语言重用 代码的扩展: 命名约定:在定义泛型类的时候最好使用T进行类型替代。 */ using System.Collections; using System.Collections.Generic; namespace Frank { public class Test { public static void Main(string[] args) { List<int> li = new List<int>(); LinkedList<int> ll = new LinkedList<int>(); ll.AddLast(1); foreach(int item in ll) { System.Console.WriteLine(item); } } } } //创建泛型类 public class LinkedListNode<T> { public LinkedListNode(T value) { this.Value = value; } public T Value{get;internal set;} public LinkedListNode<T> Next {get;internal set;} public LinkedListNode<T> Prev {get;internal set;} } //创建泛型类 public class LinkedList<T>:IEnumerable<T> { public LinkedListNode<T> First{get;private set;} public LinkedListNode<T> Last{get;private set;} //添加到最后方法 public LinkedListNode<T> AddLast(T node) { LinkedListNode<T> newNode = new LinkedListNode<T>(node); if(First == null) { First = newNode; newNode.Prev = Last; Last = First; } else { LinkedListNode<T> pervious = Last; Last.Next = newNode; Last = newNode; Last.Prev = pervious; } return newNode; } public IEnumerator<T> GetEnumerator() { LinkedListNode<T> current = First; while(current != null) { yield return current.Value;//返回当前的值 current = current.Next;//移动到下一个值 } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } }