链表 泛型链表

 链表

class Program
    {
        static void Main(string[] args)
        {
        //当然 这里 还可以加 string 等 其他类型 LinkedList
<int> li = new LinkedList<int>(); for (int i = 0; i < 10; i++) { li.AddFirst(i); } LinkedList list = new LinkedList(); list.AddFirst(4); list.AddFirst(50); list.AddFirst(3); foreach (var i in li) { Console.WriteLine(i); } Console.ReadLine(); } } public class LinkedList<T> :IEnumerable<T> { private LinkedListNode<T> first; public LinkedListNode<T> First { get { return first; } } private LinkedListNode<T> last; public LinkedListNode<T> Last { get { return last; } } public LinkedListNode<T> AddFirst(T node) { LinkedListNode<T> newNode = new LinkedListNode<T>(node); if (first==null) { first = newNode; last = first; } else { last.Next = newNode; last = newNode; } return newNode; } public IEnumerator<T> GetEnumerator() { LinkedListNode<T> curr = first; while (curr!=null) { yield return curr.Value; curr = curr.Next; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } /// <summary> /// 泛型 LinkListNode /// </summary> /// <typeparam name="T"></typeparam> public class LinkedListNode<T> { private T value; public LinkedListNode(T value) { this.value =value; } public T Value { get { return value; } } private LinkedListNode<T> next; public LinkedListNode<T> Next { get { return next; } internal set { next = value; } } private LinkedListNode<T> prev; public LinkedListNode<T> Prev { get { return prev; } internal set { prev = value; } } } /// <summary> /// /// </summary> public class LinkedList { private LinkedListNode first; public LinkedListNode First { get { return first; } } private LinkedListNode last; public LinkedListNode Last { get { return last; } } public LinkedListNode AddFirst(object val) { LinkedListNode node = new LinkedListNode(val); //链表的头 是空的 把这个节点 放在头部, // 否则放在尾部 把 链表的最后一个变成这个节点 if (first==null) { first = node; last = first; } else { last.Next = node; last = node; } return node; } public IEnumerator GetEnumerator() { LinkedListNode curr = first; while (curr != null) { yield return curr.Value; curr = curr.Next; } } } public class LinkedListNode { private object value; public LinkedListNode(object val) { this.value = val; } public object Value { get { return value; } } private LinkedListNode next; public LinkedListNode Next { get { return next; } internal set { next = value; } } private LinkedListNode prev; public LinkedListNode Prev { get { return prev; } internal set { prev = value; } } }

 

posted @ 2017-05-17 16:43  十年磨一磨霎时快如箭  阅读(144)  评论(0编辑  收藏  举报