本文共 2499 字,大约阅读时间需要 8 分钟。
** interface IList{ bool IsEmpty(); int GetLength(); void Push(T elem); void Pop(); T peek(); void Clear(); void Traverse(); }**
class Stack: IList { 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 sum=new Stack (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(); } }
转载地址:http://tdrxo.baihongyu.com/