All algorithms
Data Structures

Stack and Queue

Last-in-first-out versus first-in-first-out, side by side.

TimeO(1) per operationSpaceO(n)CategoryData Structures

A stack removes the most recently added element (LIFO); a queue removes the oldest (FIFO). Both support push and pop in constant time — the only difference is which end comes out, and that single difference changes everything built on top.

It is why DFS and BFS are the same algorithm with different containers: swap the stack for a queue and depth-first exploration becomes level-by-level. Stacks also drive function calls, undo history and bracket matching; queues drive schedulers and buffers.

Pushing the same four values into both and draining them makes the contrast immediate. AlgoLens draws both containers so you watch one reverse the input while the other preserves it.

The code

stack_and_queue.cpp
#include <bits/stdc++.h>
using namespace std;

int main() {
    stack<int> st;
    queue<int> q;

    for (int x : {1, 2, 3, 4}) {
        st.push(x);
        q.push(x);
    }

    while (!st.empty()) {
        cout << st.top() << ' ';
        st.pop();
    }
    cout << '\n';

    while (!q.empty()) {
        cout << q.front() << ' ';
        q.pop();
    }
    cout << '\n';
    return 0;
}
Open this in the visualizer

Now run your own Stack and Queue

AlgoLens traces your code — arrays, graphs, trees and recursion — from a real execution, so you see how it actually behaves, not a canned animation.

Paste your code

Keep going