public class ArrayStack<T>
{
int maxSize;//栈的大小
T[] stack;//数组模拟栈,数据就放在该数组
int top = -1;//表示栈顶,初始化为-1
public ArrayStack(int maxSize)
{
this.maxSize = maxSize;
stack = new T[this.maxSize];
}
//栈满
public bool isFull()
{
return top == maxSize - 1;
}
//栈空
public bool isEmpty()
{
return top == -1;
}
//入栈push
public void push(T value)
{
if (isFull())
{
Console.WriteLine("栈满");
return;
}
stack[++top] = value;
}
//出栈pop,将栈顶的数据返回
public T pop()
{
if (isEmpty())
{
throw new Exception("栈空");
}
return stack[top--];
}
//显示栈的数据,遍历栈,需要从栈顶开始显示数据
public void list()
{
if (isEmpty())
{
Console.WriteLine("栈空");
return;
}
for(int i = top; i >= 0; i--)
{
Console.WriteLine(stack[i]);
}
}
//返回栈头
public T peak()
{
if (isEmpty())
{
return default(T);
}
return stack[top];
}
}