Giới thiệu
Lớp Queue<T> trong namespace System.Collections.Generic đại diện cho cấu trúc dữ liệu FIFO (First In, First Out). Để kiểm tra sự tồn tại của một phần tử, ta sử dụng phương thức Contains(T item). Phương thức này thực hiện duyệt tuyến tính O(n).
Ví dụ 1
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
Queue queue = new Queue();
queue.Enqueue("Electronics");
queue.Enqueue("Accessories");
queue.Enqueue("Toys");
queue.Enqueue("Books");
queue.Enqueue("Furniture");
queue.Enqueue("Clothing");
queue.Enqueue("Footwear");
queue.Enqueue("Cookware");
queue.Enqueue("Pet Supplies");
Console.WriteLine("Các phần tử trong Queue (theo thứ tự FIFO):");
foreach (var element in queue)
{
Console.WriteLine(element);
}
Console.WriteLine("Queue có chứa phần tử 'Books'? = " + queue.Contains("Books"));
}
}
Kết quả
Các phần tử trong Queue (theo thứ tự FIFO): Electronics Accessories Toys Books Furniture Clothing Footwear Cookware Pet Supplies Queue có chứa phần tử 'Books'? = True
Ví dụ 2
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
Queue queue = new Queue();
queue.Enqueue(100);
queue.Enqueue(200);
queue.Enqueue(300);
queue.Enqueue(400);
queue.Enqueue(500);
queue.Enqueue(600);
queue.Enqueue(700);
queue.Enqueue(800);
queue.Enqueue(1000);
Console.WriteLine("Các phần tử trong Queue (theo thứ tự FIFO):");
foreach (var element in queue)
{
Console.WriteLine(element);
}
Console.WriteLine("Queue có chứa phần tử 50? = " + queue.Contains(50));
}
}
Kết quả
Các phần tử trong Queue (theo thứ tự FIFO): 100 200 300 400 500 600 700 800 1000 Queue có chứa phần tử 50? = False
Lưu ý quan trọng
- Queue duyệt theo thứ tự FIFO (phần tử thêm trước được lấy trước).
- Phương thức
Contains()có độ phức tạp O(n). - Nếu cần tìm kiếm thường xuyên, cân nhắc sử dụng
HashSet<T>song song hoặc chuyển sangList<T>. - Queue không hỗ trợ truy cập ngẫu nhiên theo chỉ mục.