Let’s go through Queues and Stacks in C# β€” two fundamental data structures in programming.


πŸ“Œ 1. Stack

A Stack is a Last-In, First-Out (LIFO) collection.

  • Last element added is the first to be removed

  • Common operations: Push, Pop, Peek

  • Part of System.Collections.Generic

Example

using System;
using System.Collections.Generic;
 
Stack<int> stack = new Stack<int>();
 
// Add elements
stack.Push(10);
stack.Push(20);
stack.Push(30);
 
// Access top element without removing
Console.WriteLine(stack.Peek()); // 30
 
// Remove top element
Console.WriteLine(stack.Pop());  // 30
Console.WriteLine(stack.Pop());  // 20
 
// Remaining element
Console.WriteLine(stack.Peek()); // 10

Key Methods

  • Push(item) β†’ Add item to top

  • Pop() β†’ Remove and return top item

  • Peek() β†’ Return top item without removing

  • Count β†’ Number of elements


πŸ“Œ 2. Queue

A Queue is a First-In, First-Out (FIFO) collection.

  • First element added is the first to be removed

  • Common operations: Enqueue, Dequeue, Peek

  • Part of System.Collections.Generic

Example

Queue<string> queue = new Queue<string>();
 
// Add elements
queue.Enqueue("Alice");
queue.Enqueue("Bob");
queue.Enqueue("Charlie");
 
// Access front element without removing
Console.WriteLine(queue.Peek()); // Alice
 
// Remove front element
Console.WriteLine(queue.Dequeue()); // Alice
Console.WriteLine(queue.Dequeue()); // Bob
 
// Remaining element
Console.WriteLine(queue.Peek()); // Charlie

Key Methods

  • Enqueue(item) β†’ Add item to end

  • Dequeue() β†’ Remove and return item from front

  • Peek() β†’ Return front item without removing

  • Count β†’ Number of elements


πŸ“Œ 3. Comparison Table

FeatureStackQueue
OrderLIFO (Last In, First Out)FIFO (First In, First Out)
Main OperationsPush, Pop, PeekEnqueue, Dequeue, Peek
Use Case ExampleUndo/Redo, Browser HistoryPrint Queue, Task Scheduling

βœ… Tips

  • Use Stack for backtracking algorithms (undo, recursion, parsing)

  • Use Queue for processing tasks in order (FIFO scheduling, BFS in graphs)

  • Both are generic in C# and part of System.Collections.Generic