C# provides two essential data structures for managing collections: Queue and Stack. These structures offer unique ways to organize and access data, each with its own specific use cases.
A Queue is a first-in-first-out (FIFO) data structure. It's like a line of people waiting for a service - the first person to join the queue is the first to be served.
using System;
using System.Collections.Generic;
Queue<string> customerQueue = new Queue<string>();
customerQueue.Enqueue("Alice");
customerQueue.Enqueue("Bob");
customerQueue.Enqueue("Charlie");
Console.WriteLine(customerQueue.Dequeue()); // Output: Alice
Console.WriteLine(customerQueue.Peek()); // Output: Bob
A Stack is a last-in-first-out (LIFO) data structure. Think of it as a stack of plates - you add and remove plates from the top.
using System;
using System.Collections.Generic;
Stack<int> numberStack = new Stack<int>();
numberStack.Push(1);
numberStack.Push(2);
numberStack.Push(3);
Console.WriteLine(numberStack.Pop()); // Output: 3
Console.WriteLine(numberStack.Peek()); // Output: 2
The choice between Queue and Stack depends on your specific use case:
Both Queue and Stack in C# offer O(1) time complexity for their core operations (Enqueue/Dequeue for Queue, Push/Pop for Stack). This makes them efficient choices for managing collections with specific access patterns.
The standard Queue and Stack implementations in C# are not thread-safe. For concurrent scenarios, consider using C# Concurrent Collections like ConcurrentQueue and ConcurrentStack.
To further enhance your understanding of data structures in C#, explore these related topics:
By mastering Queue and Stack, you'll have powerful tools at your disposal for solving various programming challenges efficiently.