Stack<T> (ใน System.Collections.Generic) มี property Count คืนค่าจำนวนสมาชิกในสแท็ก ทำงานใน O(1) ใช้ร่วมกับ Push (เพิ่ม), Pop (นำออก), Peek (ดูค่าบนสุด) และ Clear (ลบทั้งหมด)
ตัวอย่างโค้ดที่ 1: สตริง
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
Stack stack = new Stack();
stack.Push("A");
stack.Push("B");
stack.Push("C");
stack.Push("D");
stack.Push("E");
stack.Push("F");
stack.Push("G");
stack.Push("H");
Console.WriteLine("Count of elements = " + stack.Count);
Console.WriteLine("Elements in Stack...");
foreach (string res in stack)
{
Console.WriteLine(res);
}
stack.Clear();
Console.Write("Count of elements (updated) = " + stack.Count);
}
}
ผลลัพธ์
Count of elements = 8
Elements in Stack...
H
G
F
E
D
C
B
A
Count of elements (updated) = 0
ตัวอย่างโค้ดที่ 2: จำนวนเต็ม
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
Stack stack = new Stack();
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("Elements in Stack...");
foreach (int res in stack)
{
Console.WriteLine(res);
}
}
}
ผลลัพธ์
Count of elements = 10
Elements in Stack...
100
90
80
70
60
50
40
30
20
10
เมธอดและ Property สำคัญของ Stack<T>
| Member | คำอธิบาย | Complexity |
|---|---|---|
Count | จำนวนสมาชิก | O(1) |
Push(T) | เพิ่มที่บนสุด | O(1) amortized |
Pop() | นำออกและคืนค่าบนสุด | O(1) |
Peek() | ดูค่าบนสุด (ไม่ลบ) | O(1) |
Clear() | ลบทั้งหมด | O(n) |
Contains(T) | ตรวจสอบมีอยู่ | O(n) |
ToArray() | คัดลอกเป็น array (top to bottom) | O(n) |
ลำดับการวนลูป (Enumeration Order)
foreach บน Stack ให้ลำดับ Top to Bottom (LIFO order) - ตัวที่ Push สุดท้ายจะออกมาก่อน
Non-generic Stack (Legacy)
System.Collections.Stack - ควรหลีกเลี่ยง ใช้ Stack<T> แทน
Use Cases ของ Stack
- Undo/Redo functionality
- Expression evaluation (postfix, infix to postfix)
- Backtracking algorithms (maze, DFS)
- Function call stack simulation
- Browser history (back button)
- Balanced parentheses checking