wwewbw

博客园 首页 新随笔 联系 订阅 管理

引用自:[ 陈广.数据结构(C#语言描述)]

栈空条件:  this._size == 0
栈满条件:  this._size == this._array.Length
非空栈中的栈顶指针始终在栈顶元素的下一个位置上.

 

using System;
namespace Stack
{
    class Stack
    {
        //成员
        private object[] _array;                   //存放元素的数组
        private const int _defaultCapacity = 10;   //默认空间
        private int _size;                         //指示元素个数

        //属性
        public virtual int Count        //元素个数
        {
            get
            {
                return this._size;
            }
        }

        //构造器
        public Stack()
        {
            this._array = new object[_defaultCapacity];
            this._size = 0;

        }
        public Stack(int initialCapacity)
        {
            if (initialCapacity < 0)
            {
                throw new ArgumentOutOfRangeException("栈空间不能小于零");
            }
            if (initialCapacity < _defaultCapacity)
            {
                initialCapacity = _defaultCapacity;
            }
            this._array = new object[initialCapacity];    //分配栈空间
            this._size = 0;
        }

        //方法
        public virtual object Pop()                       //出栈
        {
            if (this._size == 0)
            {
                throw new ArgumentOutOfRangeException("栈下溢");
            }
            object obj2 = this._array[--this._size];      //取栈顶元素
            this._array[this._size] = null;               //删除栈顶元素
            return obj2;


        }
        public virtual void Push(object obj)              //进栈
        {
            if (this._size == this._array.Length)
            {
                object[] destinationArray = new object[2 * this._array.Length];    //空间满则扩容为原来的2倍
                Array.Copy(this._array, 0,destinationArray, 0,this._size);
                this._array = destinationArray;
            }

            this._array[this._size++] = obj;              //进栈

        }


    }
}

 

posted on 2010-02-09 13:21  wwewbw  阅读(789)  评论(0编辑  收藏  举报