當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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:
    500

使用 Stack.Peek() 方法從堆棧頂部獲取對象的 C# 示例

using System;
using System.Text;
using System.Collections;

namespace Test
{
    class Program
    {
        //function to print stack elements
        static void printStack(Stack s)
        {
            foreach (Object obj in s)
            {
                Console.Write(obj + " ");
            }
            Console.WriteLine();
        }

        static void Main(string[] args)
        {
            //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
            Console.WriteLine("object at the top is:" + stk.Peek());

            //printing stack elements
            Console.WriteLine("Stack elements are...");
            printStack(stk);

            //hit ENTER to exit
            Console.ReadLine();
        }
    }
}

輸出

object at the top is:500
Stack elements are...
500 400 300 200 100

參考:Stack.Peek 方法



相關用法


注:本文由純淨天空篩選整理自 Stack.Peek() method with example in C#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。