原文地址:
http://www.dingos.cn/index.php?topic=1705.0
本文讲解栈如何工作,想像一下桌子上的一对书。第一本书是放在最下面,然后逐一跌上来。
看下面的代码块,调用Push()方法将对象放入在栈的顶部。调用Pop()方法将栈顶元素删除并返回。如果栈是空的调用Pop()方法将会引发 InvalidOperationException异常。使用Peek()方法将返回栈顶元素,但不删除。
下面的示例创建一个栈,并压入几个整型对象并弹出他们。
程序输出如下。注意如何处理InvalidOperationException异常来管理栈下溢。
本文讲解栈如何工作,想像一下桌子上的一对书。第一本书是放在最下面,然后逐一跌上来。
看下面的代码块,调用Push()方法将对象放入在栈的顶部。调用Pop()方法将栈顶元素删除并返回。如果栈是空的调用Pop()方法将会引发 InvalidOperationException异常。使用Peek()方法将返回栈顶元素,但不删除。
下面的示例创建一个栈,并压入几个整型对象并弹出他们。
// 演示Stack类
using System;
using System.Collections;
class StackDemo{
static void ShowPush(Stack stack, int number){
stack.Push(number);
Console.WriteLine("Push(" + number + ")");
Console.Write("stack: ");
foreach(int i in stack)
Console.Write(i + " ");
Console.WriteLine();
}
static void ShowPop(Stack stack){
Console.Write("Pop -> ");
int number = (int) stack.Pop();
Console.WriteLine(number);
Console.Write("stack: ");
foreach(int i in stack)
Console.Write(i + " ");
Console.WriteLine();
}
public static void Main(){
Stack stack = new Stack();
foreach(int i in stack)
Console.Write(i + " ");
Console.WriteLine();
ShowPush(stack,2);
ShowPush(stack,4);
ShowPush(stack,77);
ShowPop(stack);
ShowPop(stack);
ShowPop(stack);
try{
ShowPop(stack);
}catch(InvalidOperationException){
Console.WriteLine("Stack empty.");
Console.Read();
}
}
}
using System;
using System.Collections;
class StackDemo{
static void ShowPush(Stack stack, int number){
stack.Push(number);
Console.WriteLine("Push(" + number + ")");
Console.Write("stack: ");
foreach(int i in stack)
Console.Write(i + " ");
Console.WriteLine();
}
static void ShowPop(Stack stack){
Console.Write("Pop -> ");
int number = (int) stack.Pop();
Console.WriteLine(number);
Console.Write("stack: ");
foreach(int i in stack)
Console.Write(i + " ");
Console.WriteLine();
}
public static void Main(){
Stack stack = new Stack();
foreach(int i in stack)
Console.Write(i + " ");
Console.WriteLine();
ShowPush(stack,2);
ShowPush(stack,4);
ShowPush(stack,77);
ShowPop(stack);
ShowPop(stack);
ShowPop(stack);
try{
ShowPop(stack);
}catch(InvalidOperationException){
Console.WriteLine("Stack empty.");
Console.Read();
}
}
}
程序输出如下。注意如何处理InvalidOperationException异常来管理栈下溢。
Push(2)
stack: 2
Push(4)
stack: 4 2
Push(77)
stack: 77 4 2
Pop -> 77
stack: 4 2
Pop -> 4
stack: 2
Pop ->2
stack:
Pop -> Stack empty.
stack: 2
Push(4)
stack: 4 2
Push(77)
stack: 77 4 2
Pop -> 77
stack: 4 2
Pop -> 4
stack: 2
Pop ->2
stack:
Pop -> Stack empty.