Lớp Stack trong C# biểu diễn tập hợp last-in, first-out (LIFO). Dùng khi muốn phần tử thêm cuối được lấy ra đầu tiên.
Các phương thức chính:
Push(item): Thêm phần tử vào đỉnh stack.Pop(): Lấy và xóa phần tử ở đỉnh stack.Peek(): Xem phần tử đỉnh stack không xóa.Count: Số phần tử trong stack.Clear(): Xóa toàn bộ stack.
Ví dụ hoàn chỉnh
using System;
using System.Collections;
namespace CollectionsApplication
{
class Program
{
static void Main(string[] args)
{
Stack st = new Stack();
st.Push('A');
st.Push('M');
st.Push('G');
st.Push('W');
Console.WriteLine("Current stack: ");
foreach (char c in st)
Console.Write(c + " ");
Console.WriteLine();
st.Push('V');
st.Push('H');
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 + " ");
}
}
}
Kết quả
Current stack: W G M A
The next poppable value in stack: H
Current stack: H V W G M A
Removing values
Current stack: G M A
Lưu ý: Stack trong System.Collections là non-generic. Nên dùng Stack<T> trong System.Collections.Generic cho type-safe.