自定义表链 SnakList

两种方式实现表链:第二种性能差

 

 

 

 

using System;
using System.Collections;

namespace Galaxy
{
    class Program
    {
 

        static void Main(string[] args)
        {
            SnakList<string> san = new();

            string xiaoming = "小米";
            string xiaoming1 = "1小米";
            san.SnakListAdd("dfdfdfsf1");
            san.SnakListAdd("dfdfdfsf2");
            san.SnakListAdd("dfdfdfsf3");
            san.SnakListAdd(xiaoming);
            san.SnakListAdd(xiaoming1);
            Console.WriteLine(san.Length);
            foreach (var sa in san)
            {

                Console.WriteLine(sa);


            }
        }

    }
    public class SnakList<T> : IEnumerable
    {

        private Node snakHead = null;//表链头
        private int length = 0;//计数器
        private Node snakTail = null;
        private Node current = null;// 游标
        public int Length { get => length; set => length = value; }

        public void SnakListAdd(T Tn)
        {

            Node newNode = new(Tn);

            
            /*   //第一种  栈链  先进后出
              newNode.Next = snakHead;
               snakHead = newNode;*/

            //第二种添 队列(queue)   先进先出

            if (length == 0)
            {

                snakHead = newNode;

                snakTail = newNode;

            }
            else
            {


                snakTail.Next= newNode;
                snakTail = newNode;
            }
          

            this.Length += 1;

        }
        IEnumerator IEnumerable.GetEnumerator()
        {
            current = snakHead;
            while (current is not null)
            {
                yield return current;

                current = current.Next;
            }

        }



        public T this[T sd]
        {
            get
            {

                Node se = new(sd);


                current = snakHead;
                while (current is not null)
                {
                    if (current.Date.Equals(se.Date)) return current.Date;

                    current = current.Next;
                }
                return default;

            }
        }

        //嵌套类不能申明为public类型, 使嵌套类型在外部可见违反了代码质量规则 CA1034
        //嵌套类不需要用 泛型,因为外类的泛型参数在子类可以使用
        class Node
        {
            private T date;
            private Node next;
            public Node()
            {
            }

            public Node(T node)
            {


                this.date = node;
                Next = null;


            }

            public T Date { get => date; set => date = value; }
            public Node Next { get => next; set => next = value; }
            public override string ToString()
            {
                return date.ToString();


            }
        }

    }



}

 

posted @ 2021-09-24 11:50  小林野夫  阅读(55)  评论(0编辑  收藏  举报
原文链接:https://www.cnblogs.com/cdaniu/