C#集合练习题(链表LinkedList<T>)

封装一个集合
提供push(T value)在尾部添加新元素,
pop()删除并返回最后一个元素,、
shift()删除并返回第一个元素,
unshift(T value)在首位添加新元素;
底层用链表模式保存数据
实现用foreach循环自定义集合

 class MyCollecion<T> : IEnumerable<T>
    {
        LinkedList<T> arr = new LinkedList<T>();
        public LinkedListNode<T> First
        {
            get
            {
                return arr.First;
            }
        }
        //在尾部添加新元素
        public void Push(T value)
        {
            arr.AddLast(value);
        }
        //删除并返回最后一个元素
        public T Pop()
        {
            LinkedListNode<T> node = arr.Last;
            arr.RemoveLast();
            return node.Value;

        }
        //删除并返回第一个元素,
        public T Shift()
        {
            LinkedListNode<T> node = arr.First;
            arr.RemoveFirst();
            return node.Value;
        }
        //在首位添加新元素
        public void Unshift(T value)
        {
            arr.AddFirst(value);
        }

        public IEnumerator<T> GetEnumerator()
        {
            return new Enumtor<T>(this);
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            throw new NotImplementedException();
        }
    }

    /// <summary>
    /// 迭代器
    /// </summary>
    /// <typeparam name="T"></typeparam>
    internal class Enumtor<T> : IEnumerator<T>
    {
        private MyCollecion<T> myCollecion;
        LinkedListNode<T> node;

        public Enumtor(MyCollecion<T> myCollecion)
        {
            this.myCollecion = myCollecion;
            this.node = myCollecion.First;//初始化指向头节点
        }

        public T Current
        {
            get
            {
                LinkedListNode<T> tempNode = node;
                node = node.Next;

                return tempNode.Value;
            }
        }

        object IEnumerator.Current
        {
            get
            {
                
                return this;
            }
        }

        public void Dispose()
        {
            Console.WriteLine();
        }

        public bool MoveNext()
        {
            //如果节点不为空 
            if (node != null)
            {
                return true;
            }
            return false;
        }

        public void Reset()
        {
            this.node = myCollecion.First;
        }
    }

测试类

猜你喜欢

转载自blog.csdn.net/qq_42485607/article/details/81086994