Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ดึงออบเจ็กต์ที่ด้านบนของ Stack ใน C#

ภาพรวม

Stack<T> ใน namespace System.Collections.Generic เป็นคอลเลกชันแบบ LIFO (Last-In-First-Out) เมธอด Peek() คืนค่าองค์ประกอบที่ด้านบน (top) โดยไม่ลบออก ในขณะที่ Pop() จะลบและคืนค่า

ตัวอย่างที่ 1: Peek กับ Stack สตริง

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        Stack<string> stack = new Stack<string>();
        stack.Push("A");
        stack.Push("B");
        stack.Push("C");
        stack.Push("D");
        stack.Push("E");
        stack.Push("F");
        stack.Push("G");
        stack.Push("H");
        stack.Push("I");
        stack.Push("J");
        Console.WriteLine("Count of elements = " + stack.Count);
        Console.WriteLine("Element at the top of stack = " + stack.Peek());
    }
}

ผลลัพธ์

Count of elements = 10
Element at the top of stack = J

ตัวอย่างที่ 2: Peek กับ Stack ตัวเลข (เรียก Peek สองครั้ง)

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        Stack<int> stack = new Stack<int>();
        stack.Push(10);
        stack.Push(20);
        stack.Push(30);
        stack.Push(40);
        stack.Push(50);
        stack.Push(60);
        stack.Push(70);
        stack.Push(80);
        stack.Push(90);
        stack.Push(100);
        Console.WriteLine("Count of elements = " + stack.Count);
        Console.WriteLine("Element at the top of stack = " + stack.Peek());
        Console.WriteLine("Element at the top of stack = " + stack.Peek());
    }
}

ผลลัพธ์

Count of elements = 10
Element at the top of stack = 100
Element at the top of stack = 100

คำอธิบายเพิ่มเติม

  • Peek() ไม่นำออกองค์ประกอบ Count คงเดิม เรียกซ้ำได้ค่าเดิม
  • หาก Stack ว่าง Peek() และ Pop() จะโยน InvalidOperationException
  • ใช้ Count > 0 ตรวจสอบก่อน Peek/Pop เพื่อป้องกันข้อยกเว้น
  • Push() เพิ่มที่ด้านบน Pop() นำออกจากด้านบน Clear() ลบทั้งหมด
  • Stack<T> เป็น generic type-safe เร็วกว่า Stack (non-generic) เดิม