Stack เป็นโครงสร้างข้อมูลแบบ LIFO (Last-In, First-Out) - รายการที่เพิ่มเข้ามาสุดท้ายจะถูกนำออกก่อน
- Push - เพิ่มรายการเข้า Stack
- Pop - นำรายการออกจาก Stack
- Peek - ดูรายการบนสุดโดยไม่นำออก
ตัวอย่างการใช้ Stack
using System;
using System.Collections;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
Stack st = new Stack();
st.Push('H');
st.Push('I');
st.Push('J');
st.Push('K');
st.Push('L');
Console.WriteLine("Count: " + st.Count); // 5
// แสดงและนำออกทีละตัว (LIFO)
while (st.Count > 0)
{
Console.WriteLine(st.Pop());
}
}
}
}
ผลลัพธ์
Count: 5 L K J I H
Generic Stack (แนะนำให้ใช้)
using System.Collections.Generic; Stack<int> stack = new Stack<int>(); stack.Push(10); stack.Push(20); int top = stack.Peek(); // 20 int popped = stack.Pop(); // 20