Stack - โครงสร้างข้อมูล LIFO
Stack แทนคอลเลกชันแบบ Last-In, First-Out (LIFO) ใช้เมื่อต้องการเข้าถึงข้อมูลแบบ "รายการล่าสุดออกก่อน" เหมือนกองจานหรือการทำงานของ Call Stack
Properties
| Property | คำอธิบาย |
Count | จำนวนสมาชิกใน Stack |
Methods
| Method | คำอธิบาย |
Clear() | ล้างสมาชิกทั้งหมด |
Contains(obj) | ตรวจสอบว่ามีสมาชิกนี้หรือไม่ |
Peek() | ดูสมาชิกด้านบน โดยไม่เอาออก |
Pop() | นำสมาชิกด้านบนออกและคืนค่า |
Push(obj) | เพิ่มสมาชิกเข้าไปด้านบน |
ToArray() | คัดลอกเป็น Array ใหม่ |
ตัวอย่าง Stack
using System;
using System.Collections;
namespace CollectionsApplication {
class Program {
static void Main(string[] args) {
Stack st = new Stack();
st.Push('A');
st.Push('B');
st.Push('C');
st.Push('D');
Console.WriteLine("Current stack: ");
foreach (char c in st) Console.Write(c + " "); // D C B A
Console.WriteLine();
st.Push('P');
st.Push('Q');
Console.WriteLine("The next poppable value: {0}", st.Peek()); // Q
Console.WriteLine("Current stack: ");
foreach (char c in st) Console.Write(c + " "); // Q P D C B A
Console.WriteLine();
Console.WriteLine("Removing values....");
st.Pop(); // Q
st.Pop(); // P
st.Pop(); // D
Console.WriteLine("Current stack: ");
foreach (char c in st) Console.Write(c + " "); // C B A
}
}
}
ผลลัพธ์ Stack
Current stack: D C B A
The next poppable value in stack: Q
Current stack: Q P D C B A
Removing values....
Current stack: C B A
Queue - โครงสร้างข้อมูล FIFO
Queue แทนคอลเลกชันแบบ First-In, First-Out (FIFO) ใช้เมื่อต้องการประมวลผลตามลำดับที่เพิ่มเข้ามา เหมือนคิวคนรอซื้อบัตรหนัง
Methods หลัก
| Method | คำอธิบาย |
Enqueue(item) | เพิ่มสมาชิกเข้าคิว (ด้านหลัง) |
Dequeue() | นำสมาชิกหน้าคิวออกและคืนค่า |
Peek() | ดูสมาชิกหน้าคิวโดยไม่เอาออก |
Count | จำนวนสมาชิกในคิว (Property) |
Clear() | ล้างคิวทั้งหมด |
Contains(obj) | ตรวจสอบว่ามีสมาชิกนี้หรือไม่ |
Enqueue - เพิ่มข้อมูลเข้าคิว
Queue q = new Queue();
q.Enqueue("Two");
q.Enqueue("One");
Dequeue - นำข้อมูลออกจากคิว
Queue q = new Queue();
q.Enqueue("Two");
q.Enqueue("One");
// นำออกทั้งหมด
while (q.Count > 0) {
Console.WriteLine(q.Dequeue());
}
ตัวอย่าง Queue สมบูรณ์
using System;
using System.Collections;
public class Demo {
public static void Main() {
Queue q = new Queue();
q.Enqueue("First");
q.Enqueue("Second");
q.Enqueue("Third");
Console.WriteLine("Queue count: " + q.Count); // 3
Console.WriteLine("Peek: " + q.Peek()); // First
Console.WriteLine("Dequeue order:");
while (q.Count > 0) {
Console.WriteLine(q.Dequeue());
}
}
}
ผลลัพธ์ Queue
Queue count: 3
Peek: First
Dequeue order:
First
Second
Third
Stack vs Queue - สรุปความแตกต่าง
| คุณสมบัติ |
Stack (LIFO) |
Queue (FIFO) |
| หลักการ |
Last In, First Out |
First In, First Out |
| เพิ่มข้อมูล |
Push() |
Enqueue() |
| นำข้อมูลออก |
Pop() |
Dequeue() |
| ดูข้อมูล (ไม่เอาออก) |
Peek() |
Peek() |
| ตัวอย่างใช้งาน |
Undo, Call Stack, DFS |
Task Scheduler, BFS, Print Queue |
Generic Versions (แนะนำ)
// Type-safe, ไม่ต้อง boxing/unboxing
Stack intStack = new Stack();
Queue stringQueue = new Queue();