链表 泛型链表

 链表

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 :IEnumerable { private LinkedListNode first; public LinkedListNode First { get { return first; } } private LinkedListNode last; public LinkedListNode Last { get { return last; } } public LinkedListNode AddFirst(T node) { LinkedListNode newNode = new LinkedListNode(node); if (first==null) { first = newNode; last = first; } else { last.Next = newNode; last = newNode; } return newNode; } public IEnumerator GetEnumerator() { LinkedListNode curr = first; while (curr!=null) { yield return curr.Value; curr = curr.Next; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } /// /// 泛型 LinkListNode /// /// public class LinkedListNode { private T value; public LinkedListNode(T value) { this.value =value; } public T 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; } } } /// /// /// 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; } } }

 

你可能感兴趣的:(链表 泛型链表)