前言
和队列不同的是,栈是先进后出,也可以说是后进先出,就像打子弹一样。
正文
代码:
public class ArrayStack
{
public int MaxLen;
public int[] Arr;
// 设置栈顶
public int top = -1;
public ArrayStack(int MaxLen) {
this.MaxLen = MaxLen;
Arr = new int[MaxLen];
}
/// <summary>
/// 判断是否为空
/// </summary>
/// <returns></returns>
public bool isEmpty(){
return top == -1;
}
/// <summary>
/// 判断是否满了
/// </summary>
/// <returns></returns>
public bool isFull() {
return top == MaxLen - 1;
}
/// <summary>
/// 放入元素
/// </summary>
public void push(int ele)
{
if (isFull())
{
throw new Exception("栈满了");
}
top++;
Arr[top] = ele;
}
public int pull() {
if (isEmpty())
{
throw new Exception("栈为空");
}
int reult=Arr[top];
top--;
return reult;
}
public void showStack()
{
if (isEmpty())
{
return;
}
for (int i = top; i >= 0; i--)
{
Console.WriteLine(Arr[top]);
}
}
}