Stack.Pop()方法用于从堆栈顶部删除对象。该方法从顶部删除并返回对象。
语法:
Object Stack.Pop();
参数:无
返回值: Object –返回从顶部删除的项目。
示例
declare and initialize a stack: Stack stk = new Stack(); insertting elements: stk.Push(100); stk.Push(200); stk.Push(300); stk.Push(400); stk.Push(500); popping stack elements: stk.Pop(); stk.Pop(); stk.Pop(); Output: 200 100
using System;
using System.Text;
using System.Collections;
namespace Test
{
class Program
{
//打印堆栈元素的功能
static void printStack(Stack s)
{
foreach (Object obj in s)
{
Console.Write(obj + " ");
}
Console.WriteLine();
}
static void Main(string[] args)
{
//声明并初始化堆栈
Stack stk = new Stack();
//插入元素
stk.Push(100);
stk.Push(200);
stk.Push(300);
stk.Push(400);
stk.Push(500);
//打印堆栈元素
Console.WriteLine("Stack elements before popping are...");
printStack(stk);
//弹出堆栈元素
object item = 0;
item = stk.Pop();
Console.WriteLine(item + " is popped");
item = stk.Pop();
Console.WriteLine(item + " is popped");
item = stk.Pop();
Console.WriteLine(item + " is popped");
//打印堆栈元素
Console.WriteLine("Stack elements after popping are...");
printStack(stk);
//按ENTER退出
Console.ReadLine();
}
}
}输出结果
Stack elements before popping are... 500 400 300 200 100 500 is popped 400 is popped 300 is popped Stack elements after popping are... 200 100
参考:Stack.Pop方法