C#中Stack.Peek()方法示例
C#方法Stack.Peek()
stack.peek()方法用于从堆栈中获取顶部对象。在stack.pop()方法中,我们已经讨论过它从顶部返回对象并删除对象,但是stack.peek()方法返回顶部对象,而不将其从堆栈中删除。
语法:
Object Stack.Peek();
参数:无
返回值: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);
printig stack's top object/element:
stk.Peek();
Output:
500C#示例使用方法从堆栈顶部获取对象Stack.Peek()
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);
//printig堆栈的顶部对象/元素
Console.WriteLine("object at the top is : " + stk.Peek());
//打印堆栈元素
Console.WriteLine("Stack elements are...");
printStack(stk);
//按ENTER退出
Console.ReadLine();
}
}
}输出结果
object at the top is : 500 Stack elements are... 500 400 300 200 100