** interface IList<T>
{
bool IsEmpty();
int GetLength();
void Push(T elem);
void Pop();
T peek();
void Clear();
void Traverse();
}**
class Stack<T> : IList<T>
{
private T[] data;
private int maxSize;
private int top;
private int under;
public Stack(int maxSize)
{
this.maxSize = maxSize;
data=new T[maxSize];
top = under = 0;
}
public void Clear()
{
data = null;
top = 0;
}
public int GetLength()
{
return top - under;
}
public bool IsEmpty()
{
return top == under;
}
//获取数据不删除
public T peek()
{
int temp = top;
if (temp==under)
{
throw new Exception("空栈取不了数据");
}
return data[temp-1];
}
public void Pop()
{
//判断栈是否为空
//获取栈顶元素
//top--
if (top == under)
{
throw new Exception("空栈遍历不了");
}
top--;
}
public void Push(T elem)
{
//判断栈是否已满
//元素压栈
//栈顶加一
if (top-under>maxSize)
{
throw new OutOfMemoryException();
}
data[top] = elem;
top++;
}
//遍历
public void Traverse()
{
int temp = top;
if (top==under)
{
throw new Exception("空栈遍历不了");
}
while (temp>0)
{
temp--;
Console.Write(data[temp]+" ");
}
}
}
class Program
{
static void Main(string[] args)
{
Stack<int> sum=new Stack<int>(10);
Console.WriteLine(sum.IsEmpty());
Console.WriteLine(sum.GetLength());
sum.Push(0);
sum.Push(1);
sum.Push(2);
sum.Push(3);
sum.Push(4);
sum.Push(5);
sum.Push(6);
sum.Push(7);
Console.WriteLine("sum.peek:"+sum.peek());
Console.WriteLine(sum.GetLength());
sum.Traverse();
Console.WriteLine();
sum.Pop();
sum.Pop();
Console.WriteLine("sum.GetLength" + sum.GetLength());
sum.Traverse();
Console.ReadKey();
}
}