Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Lấy đối tượng tại đỉnh Stack trong C#

Giới thiệu

Stack<T> (namespace System.Collections.Generic) là cấu trúc LIFO (Last In, First Out). Phương thức Peek() trả về phần tử ở đỉnh stack không xóa nó. Pop() cũng trả về đỉnh nhưng xóa nó.

Ví dụ 1: Peek() trên Stack chuỗi

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());
    }
}

Kết quả

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

Ví dụ 2: Peek() nhiều lần không làm thay đổi stack

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());
        Console.WriteLine("Count after two Peek = " + stack.Count);
    }
}

Kết quả

Count of elements = 10
Element at the top of stack = 100
Element at the top of stack = 100
Count after two Peek = 10

So sánh Peek() vs Pop()

Phương thức Trả về đỉnh Xóa đỉnh Ném exception nếu rỗng
Peek() Có Không InvalidOperationException
Pop() Có Có InvalidOperationException
TryPeek() (.NET Core 2.0+) out T Không Không (trả về bool)
TryPop() (.NET Core 2.0+) out T Có Không (trả về bool)

Ví dụ an toàn với TryPeek

Stack<int> stack = new Stack<int>();

if (stack.TryPeek(out int top))
{
    Console.WriteLine("Top: " + top);
}
else
{
    Console.WriteLine("Stack is empty");
}

// So với cách cũ
if (stack.Count > 0)
{
    Console.WriteLine("Top: " + stack.Peek());
}

Ứng dụng thực tế

  • Undo/Redo functionality
  • Expression evaluation (postfix, prefix)
  • Backtracking algorithms
  • Browser history (forward/back)
  • Function call stack simulation