【C#数据结构】单链表

C#实现

首先,构造一个单链表的节点类:

    class Link
    {
        public T Data;
        public Link Next;
        /// 
        /// 构造函数
        /// 
        /// 
        /// 
        public Link(T data, Link next = null)
        {
            Data = data;
            Next = next;
        }
    }

然后是以这个节点类为基础,创建单链表类:这里简单实现了单链表的两个功能添加和输出

    class LinkList
    {
        Link Head = new Link(default(T), null);
        /// 
        /// 增加数据
        /// 
        public void AddData(T Data)
        {
            Link link = new Link(Data);

            if (link.Data.GetType() != Head.Data.GetType())
            {
                throw new Exception("添加的类型和之前的不一样");
            }
            if (Head.Next == null)
            {
                Head.Next = link;
            }
            else if (Head.Next != null)
            {
                link.Next = Head.Next;
                Head.Next = link;
            }
        }
        /// 
        /// 打印全部数据
        /// 
        public void PrintAllData()
        {
            Link TempHead = Head;
            while (TempHead.Next != null)
            {
                Console.WriteLine(TempHead.Next.Data);
                TempHead = TempHead.Next;
            }
        }
    }

测试的话,可以拿下面这个Main函数测试:

class MainTest
    {
        static void Main(string[] args)
        {
            LinkList Test = new LinkList();
            int[] array = { 1, 25, 12, 33, 26, 33, 63 };
            for (int i = 0; i < array.Length; i++)
            {
                Test.AddData(array[i]);
            }
            Test.PrintAllData();
        }
    }

 

你可能感兴趣的:(算法)