节点类(LinkedListNode)
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace List { public class LinkedListNode<T> { public T Value { get; private set; } /// <summary> /// 后一个节点 /// </summary> public LinkedListNode<T> Next { get; internal set; } /// <summary> /// 前一个节点 /// </summary> public LinkedListNode<T> Prev { get; internal set; } public LinkedListNode(T value) { this.Value = value; } } }
节点列表类(LinkedList)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; namespace List { public class LinkedList<T>:IEnumerable<T> { /// <summary> /// 链表的头 /// </summary> public LinkedListNode<T> First { get; private set; } /// <summary> /// 链表的尾 /// </summary> public LinkedListNode<T> Last { get; private set; } /// <summary> /// 增加节点 /// </summary> /// <param name="node"></param> /// <returns></returns> public LinkedListNode<T> AddLast(T node) { var newNode = new LinkedListNode<T>(node); //构造节点(每个节点两个属性Next和Prev) if (First == null) { First = newNode; Last = First; } else { LinkedListNode<T> previous = Last; //链表的尾赋给节点previous Last.Next = newNode; //当前链表的最后一个节点指向新节点 Last = newNode; //将新节点赋给链表的最后一个节点 Last.Prev = previous; //链表的新节点指向上次添加的节点 } return newNode; } /// <summary> /// 遍历节点 /// </summary> /// <returns></returns> public IEnumerator<T> GetEnumerator() { LinkedListNode<T> current = First; while (current != null) { yield return current.Value; //yield创建一个枚举器的状态机 current = current.Next; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
测试类(Main)
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace List { class Program { static void Main(string[] args) { //用int实例化 var list = new LinkedList<int>(); list.AddLast(1); list.AddLast(2); list.AddLast(3); foreach (int i in list) { Console.WriteLine(i); } //用string实例化 var list1 = new LinkedList<string>(); list1.AddLast("first"); list1.AddLast("second"); list1.AddLast("third"); foreach (string str in list1) { Console.WriteLine(str); } } } }
运行结果