//栈空条件: this._size == -1
//栈满条件: this.Count == this._array.Length
//自己改了一下, this._size 直接指向栈顶元素
using System;
namespace Stack
{
class Stack2
{
//成员
private object[] _array; //存放元素的数组
private const int _defaultCapacity = 10; //默认空间
private int _size; //指向栈顶元素
//属性
public virtual int Count //元素个数
{
get
{
return (this._size + 1);
}
}
//构造器
public Stack2()
{
this._array = new object[_defaultCapacity];
this._size = -1;
}
public Stack2(int initialCapacity)
{
if (initialCapacity < 0)
{
throw new ArgumentOutOfRangeException("栈空间不能小于零");
}
if (initialCapacity < _defaultCapacity)
{
initialCapacity = _defaultCapacity;
}
this._array = new object[initialCapacity]; //分配栈空间
this._size = -1;
}
//方法
public virtual object Pop() //出栈
{
if (this._size == -1)
{
throw new ArgumentOutOfRangeException("栈下溢");
}
object obj2 = this._array[this._size]; //取栈顶元素
this._array[this._size--] = null; //删除栈顶元素
return obj2;
}
public virtual void Push(object obj) //进栈
{
if (this.Count == this._array.Length)
{
object[] destinationArray = new object[2 * this._array.Length]; //空间满则扩容为原来的2倍
Array.Copy(this._array, 0, destinationArray, 0, this.Count );
this._array = destinationArray;
}
this._array[++this._size] = obj; //进栈
}
}
}