用一片连续的存储空间来存储栈中的数据元素,这样的栈称为顺序栈。类似顺序表,用一维数组来存放顺序栈中的数据元素。栈顶指示器top设在数组下标为0的端,top随着插入和删除而变化,当栈为空时,top=-1。
public interface IStack
{
int Count { get; }
int GetLength();
bool IsEmpty();
void Push(T item);
T Pop();
T Peek();
}
class SequStack : IStack
{
private T[] data;
private int top;
public SequStack(int size)
{
data = new T[size];
top = -1;
}
public SequStack():this(10)
{
}
public int Count
{
get {
return top + 1;
}
}
public int GetLength()
{
return Count;
}
public bool IsEmpty()
{
return Count == 0;
}
public T Peek()
{
return data[top];
}
public T Pop()
{
T teamp = data[top];
top--;
return teamp;
}
public void Push(T item)
{
data[top + 1] = item;
top++;
}
}