C#泛型链表Demo
/// <summary> /// 节点 /// </summary> /// <typeparam name="T"></typeparam> public class LinkedListNode<T> { public LinkedListNode(T value) { this.Value = value; } 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 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) { var newNode = new LinkedListNode<T>(node); if(First == null) { First = newNode; Last = First; } else { LinkedListNode<T> previous = Last; Last.Next = newNode; Last = newNode; Last.Prev = previous; } 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(); } }
static void Main(string[] args) { try { Console.WriteLine("**********************LinkedList<int>*********************"); var list1 = new LinkedList<int>(); list1.AddLast(1); list1.AddLast(3); list1.AddLast(5); list1.AddLast(7); foreach (var item in list1) { Console.WriteLine(item); } Console.WriteLine("*********************LinkedList<string>**********************"); var list2 = new LinkedList<string>(); list2.AddLast("2"); list2.AddLast("aaaa"); list2.AddLast("bbbbb"); list2.AddLast("cccc"); foreach (var item in list2) { Console.WriteLine(item); } } catch (Exception ex) { Console.WriteLine("程序出现错误:" + ex.Message); } Console.ReadKey(); }