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

Stack Class ใน C# - คู่มือครบถ้วน

Stack Class ใน C# แทนคอลเลกชันแบบ LIFO (Last-In, First-Out) ใช้เมื่อต้องการเข้าถึงข้อมูลแบบ "รายการที่เพิ่มล่าสุด จะถูกนำออกก่อน" อยู่ใน Namespace System.Collections (Non-generic) และ System.Collections.Generic (Generic Stack<T>)

Properties

Property คำอธิบาย
Count จำนวนสมาชิกใน Stack (Read-only)

Methods

Method Signature คำอธิบาย
Clear public virtual void Clear() ล้างสมาชิกทั้งหมดออกจาก Stack
Contains public virtual bool Contains(object obj) ตรวจสอบว่ามีสมาชิกระบุอยู่ใน Stack หรือไม่
Peek public virtual object Peek() คืนค่าสมาชิกด้านบน (Top) โดยไม่เอาออก โยน Exception ถ้าว่าง
Pop public virtual object Pop() นำสมาชิกด้านบนออกและคืนค่า โยน Exception ถ้าว่าง
Push public virtual void Push(object obj) เพิ่มสมาชิกเข้าไปด้านบน (Top) ของ Stack
ToArray public virtual object[] ToArray() คัดลอกสมาชิกทั้งหมดเป็น Array ใหม่ (Top เป็น Index 0)

ตัวอย่างการใช้งาน

using System;
using System.Collections;

public class Demo {
    public static void Main() {
        Stack st = new Stack();
        
        // Push - เพิ่มข้อมูล
        st.Push('A');
        st.Push('B');
        st.Push('C');
        st.Push('D');
        
        Console.WriteLine("Count: " + st.Count);  // 4
        Console.WriteLine("Top (Peek): " + st.Peek());  // D
        
        // Iterate (Top to Bottom)
        Console.Write("Stack contents: ");
        foreach (object item in st) {
            Console.Write(item + " ");  // D C B A
        }
        Console.WriteLine();
        
        // Pop - นำออก
        Console.WriteLine("Pop: " + st.Pop());  // D
        Console.WriteLine("Pop: " + st.Pop());  // C
        Console.WriteLine("Remaining Count: " + st.Count);  // 2
        
        // Contains
        Console.WriteLine("Contains 'B': " + st.Contains('B'));  // True
        
        // ToArray
        object[] arr = st.ToArray();  // [B, A] - Top first
        
        // Clear
        st.Clear();
        Console.WriteLine("After Clear, Count: " + st.Count);  // 0
    }
}

Generic Stack<T> (แนะนำใช้)

using System.Collections.Generic;

Stack numbers = new Stack();
numbers.Push(10);
numbers.Push(20);
numbers.Push(30);

int top = numbers.Pop();  // 30 - ไม่ต้อง Cast
int peek = numbers.Peek(); // 20

// Type-safe, No Boxing/Unboxing, Better Performance

Use Cases (กรณีการใช้งานจริง)

Use Case คำอธิบาย
Undo/Redo เก็บ State ก่อนหน้าเพื่อย้อนกลับ
Expression Evaluation คำนวณ Postfix/Prefix Notation
Backtracking Maze Solving, N-Queens, DFS
Browser History Back Button (Stack of URLs)
Function Call Stack Compiler/Runtime จัดการให้อัตโนมัติ
Syntax Parsing Matching Parentheses, Tags

ตัวอย่าง: Parentheses Matching

public static bool IsBalanced(string input) {
    var stack = new Stack();
    var pairs = new Dictionary {
        { ')', '(' }, { ']', '[' }, { '}', '{' }
    };
    
    foreach (char c in input) {
        if ("([{".Contains(c)) {
            stack.Push(c);
        } else if (")]}".Contains(c)) {
            if (stack.Count == 0 || stack.Pop() != pairs[c])
                return false;
        }
    }
    return stack.Count == 0;
}

// Test
Console.WriteLine(IsBalanced("{[()]}"));  // True
Console.WriteLine(IsBalanced("{[(])}"));  // False

Exception Handling

Stack s = new Stack();

// Pop/Peek บน Stack ว่าง -> InvalidOperationException
try {
    int x = s.Pop();
} catch (InvalidOperationException) {
    Console.WriteLine("Stack is empty!");
}

// Safe Pattern
if (s.Count > 0) {
    int x = s.Pop();
}

// หรือใช้ TryPop (C# 9+ / .NET 5+)
if (s.TryPop(out int value)) {
    Console.WriteLine(value);
}