引用自:[ 陈广.数据结构(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 &#61; _defaultCapacity;
}
this._array &#61; new object[initialCapacity]; //分配栈空间
this._size &#61; 0;
}
//方法
public virtual object Pop() //出栈
{
if (this._size &#61;&#61; 0)
{
throw new ArgumentOutOfRangeException("栈下溢");
}
object obj2 &#61; this._array[--this._size]; //取栈顶元素
this._array[this._size] &#61; null; //删除栈顶元素
return obj2;
}
public virtual void Push(object obj) //进栈
{
if (this._size &#61;&#61; this._array.Length)
{
object[] destinationArray &#61; new object[2 * this._array.Length]; //空间满则扩容为原来的2倍
Array.Copy(this._array, 0,destinationArray, 0,this._size);
this._array &#61; destinationArray;
}
this._array[this._size&#43;&#43;] &#61; obj; //进栈
}
}
}