c# 栈

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35759688/article/details/77844880
    public class MyStack<T>
    {
        private T[] _stack;
        private int _count;
        private int _capacity;
        private int _top;

        public int Count
        {
            get { return _count; }
        }

        public int Capacity
        {
            get { return _capacity; }
        }

        public MyStack(int Capacity)
        {
            _capacity = Capacity;
            _stack =new T[_capacity];
            _count = 0;
            _top = -1;
        }

        public T Peek()
        {
            if (IsEmpty())
            {
                Console.WriteLine("Stack Is IsEmpty!");
                return default(T);
            }
            return _stack[_top];
        }

        public T Pop()
        {
            if (IsEmpty())
            {
                Console.WriteLine("Stack Is Empty!");
                return default(T);
            }
            T temp = _stack[_top];
            _top --;
            _count--;
            return temp;
        }

        public void Push(T item)
        {
            if (IsFull())
            {
                Console.WriteLine("Stack Is Full!");
                return;
            }
            _top ++;
            _count++;
            _stack[_top] = item;
        }

        public bool IsFull()
        {
            return _count == _capacity;
        }

        public bool IsEmpty()
        {
            return _count == 0;
        }

        public void Clear()
        {
            Array.Clear(_stack,0,_count);
            _count = 0;
            _top = -1;
        }

        public void DisPlay()
        {
            if(IsEmpty()) Console.WriteLine("Stack is Empty!!!");
            for (int i = 0; i < _count; i++)
            {
                Console.WriteLine(_stack[i]);
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_35759688/article/details/77844880