栈的基本运算有六种:
构造空栈:InitStack(S)、
判栈空: StackEmpty(S)、
判栈满: StackFull(S)、
进栈: Push(S,x)、可形象地理解为压入,这时栈中会多一个元素
退栈: Pop(S) 、可形象地理解为弹出,弹出后栈中就无此元素了。
取栈顶元素:StackTop(S),不同与弹出,只是使用栈顶元素的值,该元素仍在栈顶不会改变。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Stack
{
class Stack
{
private int count;
private int current;
private int[] items;
public Stack(int capacity)
{
items = new int[capacity];
this.count = 0;
this.current = 0;
}
public void Push(int item)
{
try
{
items[count]=item;
current = item;
count++;
}
catch(IndexOutOfRangeException)
{
throw new IndexOutOfRangeException("Stack is out of top. Can't push any more");
}
}
public int Pop()
{
try
{
int current = items[count-1];
items[count-1] = 0;
count--;
if (count == 0)
this.current = 0;
else if (count > 0)
this.current = items[count - 1];
return current;
}
catch (IndexOutOfRangeException)
{
throw new IndexOutOfRangeException("Stack is at bottom.Can't pop any more.");
}
}
/// <summary>
/// Return true if Stack is empty.
/// </summary>
/// <returns></returns>
public bool IsEmpty()
{
return count == 0 ? true : false;
}
/// <summary>
/// Return true if Stack is full.
/// </summary>
/// <returns></returns>
public bool IsFull()
{
return count == items.Length ? true : false;
}
public int Current
{
get { return current; }
}
}
}