C# LinkedList<T> 泛型类的实现

来源:互联网 发布:js中get post 区别 编辑:程序博客网 时间:2024/06/06 00:00

上一篇中,可以存储任意类型的数据,但是在访问所有的对象时,存储的有整形数据有字符串类型,在使用循环访问所有的对象时,无法将数据转换成统一的类型,这就会报错。

具体的参考C#高级编程第8版。


现在实现一个泛型的链表,在定义对象时,指定存储的类型,在存储数据时,只存储指定类型的数据,这样就可以实现对象的统一管理。


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace ConsoleApplication6
{
    /// <summary>
    /// 泛型类,可以包括任意类型的数据
    /// </summary>
    public class LinkedListNode<T>
    {
        public LinkedListNode(T value)
        {
            this.Value = value;
        }


        public T Value { get;private set; }
        /// <summary>
        /// Next字段就是指向下一个节点
        /// Prev指向当前节点的上一个节点
        /// </summary>
        public LinkedListNode<T> Next { get; internal set; }
        public LinkedListNode<T> Prev { get; internal set; }
    }
    /// <summary>
    /// 创建链表
    /// </summary>
    public class LinkedList<T> : IEnumerable<T>
    {
        public LinkedListNode<T> First { get; private set; }
        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);
            if (First==null)
            {
                First = newNode;
                Last = First;
            }
            else
            {
                LinkedListNode<T> previous = Last;
                Last.Next = newNode;
                Last = newNode;
                Last.Prev = previous;
            }


            return newNode;
        }
        /// <summary>
        /// 通过GetEnumerator方法使用yield创建一个枚举器类型,遍历当前链表中的所有数据 
        /// </summary>
        /// <returns></returns>
        public IEnumerator<T> GetEnumerator()
        {
            LinkedListNode<T> current = First;
            while (current!=null)
            {
                yield return current.Value;
                current = current.Next;
            }
        }




        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}


示例代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ConsoleApplication6;


namespace ConsoleApplication6
{
    class Program
    {
        static void Main(string[] args)
        {
            var list1 = new LinkedList<int>();
            list1.AddLast(1);
            list1.AddLast(2);
            list1.AddLast(7);


            foreach (var item in list1)
            {
                Console.WriteLine(item);
            }


            Console.ReadKey();
        }
    }
}

0 0
原创粉丝点击