Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Cách sử dụng lớp Stack trong C#

Lớp Stack 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 (ví dụ: chồng sách).

Các phương thức chính:

STTPhương thức & Mô tả
1Clear(): Xóa tất cả phần tử.
2Contains(obj): Kiểm tra phần tử có trong stack.
3Peek(): Xem phần tử đỉnh không xóa.
4Pop(): Lấy và xóa phần tử đỉnh.
5Push(obj): Thêm phần tử vào đỉnh.
6ToArray(): Copy stack sang mảng mới.

Thuộc tính: Count: Số phần tử hiện tại.

Ví dụ: Push, Peek, 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("Next poppable (Peek): {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: D C B A
Next poppable (Peek): Q
Current stack: Q P D C B A
Removing values...
Current stack: C B A

Khuyến nghị: Dùng Stack<T> trong System.Collections.Generic cho type-safe, tránh boxing/unboxing.