堆栈对象Stack和数据结构中的堆栈对象一样,即从顺序表的一段插入,并从这一段取出,可理解为一堆盘子,只能从盘子的上面增加和拿走盘子。
/* Example11_11.cs illustrates the use of a Stack */ using System; using System.Collections; class Example11_11 { public static void Main() { // create a Stack object Stack myStack = new Stack(); // add four elements to myStack using the Push() method myStack.Push("This"); myStack.Push("is"); myStack.Push("a"); myStack.Push("test"); // display the elements in myStack foreach (string myString in myStack) { Console.WriteLine("myString = " + myString); } // get the number of elements in myStack using the // Count property int numElements = myStack.Count; for (int count = 0; count < numElements; count++) { // examine an element in myStack using Peek() Console.WriteLine("myStack.Peek() = " + myStack.Peek()); // remove an element from myStack using Pop() Console.WriteLine("myStack.Pop() = " + myStack.Pop()); } } }