栈的顺序存储

栈的顺序存储_第1张图片栈的顺序存储_第2张图片栈的顺序存储_第3张图片
栈的顺序存储_第4张图片

栈的顺序存储_第5张图片
栈的顺序存储_第6张图片

栈的顺序存储_第7张图片

栈的顺序存储_第8张图片

** interface IList
    {
        bool IsEmpty();
        int GetLength();
        void Push(T elem);
        void Pop();
        T peek();
        void Clear();
        void Traverse();
    }**
 class Stack : IList
    {
        private T[] data;
        private int maxSize;
        private int top;
        private int under;

        public Stack(int maxSize)
        {
            this.maxSize = maxSize;
            data=new T[maxSize];
            top = under = 0;
        }
    

栈的顺序存储_第9张图片

        public void Clear()
        {
            data = null;
            top = 0;  
        }

栈的顺序存储_第10张图片

        public int GetLength()
        {
            return top - under;
        }

栈的顺序存储_第11张图片

        public bool IsEmpty()
        {
            return top == under;
        }


        //获取数据不删除
        public T peek()
        {
            int temp = top;
            if (temp==under)
            {
                throw new Exception("空栈取不了数据");
            }
           
            return data[temp-1];
        }

栈的顺序存储_第12张图片

        public void Pop()
        {
            //判断栈是否为空
            //获取栈顶元素
            //top--           
            if (top == under)
            {
                throw new Exception("空栈遍历不了");
            }
            top--;
        }

栈的顺序存储_第13张图片
栈的顺序存储_第14张图片

        public void Push(T elem)
        {
            //判断栈是否已满
            //元素压栈
            //栈顶加一

            if (top-under>maxSize)
            {
                throw new OutOfMemoryException();
            }

            data[top] = elem;
            top++;
        }

        //遍历
        public void Traverse()
        {
            int temp = top;
            if (top==under)
            {
                throw new Exception("空栈遍历不了");        
            }

            while (temp>0)
            {
                temp--;
                Console.Write(data[temp]+"  ");
            }
        }
    }
 class Program
    {
        static void Main(string[] args)
        {

            Stack sum=new Stack(10);
            Console.WriteLine(sum.IsEmpty());
            Console.WriteLine(sum.GetLength());
            sum.Push(0);
            sum.Push(1);
            sum.Push(2);
            sum.Push(3);
            sum.Push(4);
            sum.Push(5);
            sum.Push(6);
            sum.Push(7);
            Console.WriteLine("sum.peek:"+sum.peek());
            Console.WriteLine(sum.GetLength());
            sum.Traverse();
            Console.WriteLine();
            sum.Pop();
            sum.Pop();
            Console.WriteLine("sum.GetLength" + sum.GetLength());
            sum.Traverse();
            Console.ReadKey();
        }
    }

你可能感兴趣的:(数据结构)