CodeBlanks Logo Icon CodeBlanks

Queue<T> and Stack<T>

C# course · Intermediate · Lesson 79/116

Learn FIFO with Queue<T> and LIFO with Stack<T>.

FIFO with Queue<T>

A Queue<T> is a first in, first out (FIFO) sequence. Enqueue adds to the back, Dequeue removes from the front. Peek views the front without removing.

Typical uses: print queue, message queue, task list. New items enter at the back; the next item is always the front one. Calling Dequeue on an empty queue throws.

LIFO with Stack<T>

A Stack<T> is a last in, first out (LIFO) stack. Push adds to the top, Pop removes from the top. Peek views the top without removing.

Typical uses: undo stack, expression evaluation, depth-first search. The last item added is the first to leave. Calling Pop on an empty stack throws. Queue and Stack share similar interfaces but opposite ordering rules.

Exercise Queue and Stack together

The queue and stack below are ready. Call queue.Dequeue() and stack.Pop(); print each result on a separate line with Console.WriteLine.

Show example solution
Dequeue takes from the front, Pop from the top; print both with WriteLine.
Example solution:
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        var queue = new Queue<string>();
        queue.Enqueue("one");
        queue.Enqueue("two");
        queue.Enqueue("three");
        var stack = new Stack<int>();
        stack.Push(10);
        stack.Push(20);
        stack.Push(30);
        Console.WriteLine(queue.Dequeue());
        Console.WriteLine(stack.Pop());
    }
}

Test yourself

  1. Which removes the front of a queue?

    • Enqueue
    • Push
    • Pop
    • Dequeue
    Show answer

    Dequeue — Correct. Dequeue removes the front item of the queue.

  2. Complete the Enqueue call

    queue.____("one");
    Show answer
    queue.Enqueue("one");
  3. Match the method to its structure

    Enqueue
    Add to queue
    Dequeue
    Remove from queue
    Push
    Add to stack
    Pop
    Remove from stack

All lessons in Intermediate