在C#中,通过类Stack来封装对栈的操作,使得对栈的操作变得非常简单和容易理解。
栈是按照“后进先出”的原则来操作元素。
栈集合常用的属性和方法:
| 属性 | 说明 |
| Count | 获取 Stack 中包含的元素数。 |
| 方法 | 说明 |
| Peek | 返回位于栈顶部的对象但不将其移除。 |
| Pop | 移除并返回位于栈顶部的对象。 |
| Push | 将对象插入 Stack 的顶部。 |
通过方法Push、Pop就能实现栈的入栈和退栈操作,通过方法Peek就能获取栈顶的元素。
Stack类实例:
- public static void Main()
- {
- // Creates and initializes a new Stack.
- Stack myStack = new Stack();
- myStack.Push( "Cristiano" );
- myStack.Push( "is" );
- myStack.Push( "the" );
- myStack.Push( "best" );
- // Displays the Stack.
- Console.Write( "Stack values:" );
- PrintValues( myStack, '\t' );
- // Removes an element from the Stack.
- Console.WriteLine("(Pop)\t\t{0}", myStack.Pop());
- // Displays the Stack.
- Console.Write( "Stack values:" );
- PrintValues( myStack, '\t' );
- // Views the first element in the Stack but does not remove it.
- Console.WriteLine("(Peek)\t\t{0}",myStack.Peek());
- // Displays the Stack.
- Console.Write( "Stack values:" );
- PrintValues( myStack, '\t' );
- }
- public static void PrintValues(Stack myCollection,char mySeparator )
- {
- foreach ( Object obj in myCollection )
- Console.Write( "{0}{1}", mySeparator, obj );
- Console.WriteLine();
- }