Stack ใช้ LIFO (Last-In-First-Out) มีเมธอด Push และ Pop
เมธอดหลักของ Stack:
| ลำดับ | Method & Description |
|---|---|
| 1 | Clear() - ล้าง Stack |
| 2 | Contains(object) - ตรวจสอบ Element |
| 3 | Peek() - ดู Element บนสุด ไม่ลบ |
| 4 | Pop() - ลบและคืน Element บนสุด |
| 5 | Push(object) - ใส่ Element บนสุด |
| 6 | ToArray() - คัดลอกเป็น Array |
Push เพิ่มข้อมูล Pop ลบข้อมูล
ตัวอย่าง
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 + " "); }
Console.WriteLine();
st.Push('P');
st.Push('Q');
Console.WriteLine("The next poppable value in stack: {0}", st.Peek());
Console.WriteLine("Current stack: ");
foreach (char c in st) { Console.Write(c + " "); }
Console.WriteLine();
Console.WriteLine("Removing values....");
st.Pop();
st.Pop();
st.Pop();
Console.WriteLine("Current stack: ");
foreach (char c in st) { Console.Write(c + " "); }
}
}
}
ผลลัพธ์
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