Queue, Stack and priority queue
Queue, Stack and priority queue
Choose a queue, stack or priority queue by deciding which item should be removed next. All three are useful when the removal rule matters more than positional access.
Examples target the proposed C# 14 / .NET 10 console baseline. Each is a separate Program.cs; outputs are predictions pending compilation.
First in, first out
A Queue<T> models arrival order (FIFO). Enqueue appends, Dequeue removes the oldest item, and Peek reads it without removal. TryDequeue and TryPeek report empty queues without an exception. An ordinary queue does not provide thread-safe producer-consumer coordination.
using System;using System.Collections.Generic;var tickets = new Queue<string>();tickets.Enqueue("T1");tickets.Enqueue("T2");Console.WriteLine(tickets.Peek());while (tickets.TryDequeue(out string? ticket)) Console.WriteLine(ticket);Console.WriteLine(tickets.TryDequeue(out _));Peek leaves T1 at the front. Each successful removal reduces the count until the queue is empty.
Expected output (reasoned, not executed):
T1T1T2FalseLast in, first out
A Stack<T> models the most recent item first (LIFO). Push adds, Pop removes, and Peek inspects the top. TryPop and TryPeek provide Boolean success results. A simple undo history can store earlier values, although full application undo often needs richer command or snapshot data.
using System;using System.Collections.Generic;var history = new Stack<string>();history.Push("draft");history.Push("revised");Console.WriteLine(history.Pop());Console.WriteLine(history.Pop());Console.WriteLine(history.TryPop(out _));The most recently pushed value is removed first. Empty is handled explicitly.
Expected output (reasoned, not executed):
reviseddraftFalseOrder by priority and resolve ties
PriorityQueue<TElement,TPriority> (available from .NET 6) removes an element with the smallest priority according to its comparer. It does not promise FIFO among equal priorities. Use a composite priority such as (rank, sequence) when ties must respect arrival order. ValueTuple comparison compares the first component and then the second. A heap is not a fully sorted list: UnorderedItems is not a sorted output sequence.
using System;using System.Collections.Generic;var jobs = new PriorityQueue<string, (int Rank, int Arrival)>();jobs.Enqueue("report", (2, 0));jobs.Enqueue("repair", (1, 1));jobs.Enqueue("backup", (1, 2));jobs.Enqueue("cleanup", (3, 3));while (jobs.TryDequeue(out string? job, out var priority)) Console.WriteLine($"{job}:{priority.Rank}");Rank is the first ordering key. Arrival breaks the tie between repair and backup, independent of the heap’s equal-priority behavior.
Expected output (reasoned, not executed):
repair:1backup:1report:2cleanup:3Common mistakes and edge cases
Do not use Pop or Dequeue blindly on empty containers; they throw InvalidOperationException. Check success with Try methods. A larger numeric value is not a higher scheduling priority by default. Heap operations are typically logarithmic for removal and insertion (amortized considerations apply to storage growth); do not assume sorted iteration or constant-time removal.
Practice and next steps
Create a priority workflow for jobs A rank 3, B rank 1, C rank 1, D rank 2, arriving in that order. Return the processing sequence, then show that TryDequeue reports false when empty. Compare a FIFO queue with the same arrival order.
Next: Read-only and immutable collections.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Queue, Stack and priority queue — knowledge check
Apply the lesson concepts to the following scenarios.
What is removed first from a queue after enqueueing A then B?
What is removed first from a stack after pushing A then B?
What happens when Queue<T>.TryDequeue is called on an empty queue?
Which numeric priority is removed first by the default PriorityQueue comparer?
How can equal rank jobs be processed in arrival order?