C++ · Module 18 · Lesson 31 min read

Implementing a Stack & Queue

Stack (LIFO) on top of a vector

arduino
template <typename T>
class Stack {
    std::vector<T> data_;
public:
    void push(T x) { data_.push_back(std::move(x)); }
    T pop()  { if (empty()) throw ...; T top = std::move(data_.back()); data_.pop_back(); return top; }
    const T& top() const;
    bool empty() const;
};

All operations O(1) (amortized).

Circular queue (ring buffer)

A fixed-size array with head and tail indexes that wrap around:

ini
tail = (tail + 1) % capacity;
head = (head + 1) % capacity;
  • O(1) enqueue/dequeue, no shifting, no allocation after construction
  • Track count to tell "full" from "empty"
  • Used in audio buffers, network packets, keyboard input, logging the last N events

Classic stack applications

  • Bracket matching (lesson 13.5)
  • Undo/redo (two stacks)
  • Postfix (RPN) evaluation: numbers → push; operator → pop two, apply, push result
  • Infix → postfix (shunting-yard algorithm by Dijkstra) using operator precedence
  • Function call stack, DFS, backtracking

Classic queue applications

  • BFS (graph traversal)
  • Task scheduling, print spoolers
  • Simulations (customers arriving at a counter)
  • Producer–consumer buffers

Interview twist

Implement a queue using two stacks: push onto in; when out is empty, move everything from in to out; pop from out. Amortized O(1).

Example

C++
#include <cctype>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>

template <typename T>
class Stack {
public:
    void push(T x) { data_.push_back(std::move(x)); }
    T pop() {
        if (data_.empty()) throw std::underflow_error("pop from empty stack");
        T top = std::move(data_.back());
        data_.pop_back();
        return top;
    }
    bool empty() const { return data_.empty(); }
    std::size_t size() const { return data_.size(); }
private:
    std::vector<T> data_;
};

template <typename T>
class RingQueue {
public:
    explicit RingQueue(std::size_t capacity) : data_(capacity) {}
    bool enqueue(T x) {
        if (count_ == data_.size()) return false;            // full
        data_[tail_] = std::move(x);
        tail_ = (tail_ + 1) % data_.size();                  // wrap around
        ++count_;
        return true;
    }
    T dequeue() {
        if (count_ == 0) throw std::underflow_error("queue empty");
        T x = std::move(data_[head_]);
        head_ = (head_ + 1) % data_.size();
        --count_;
        return x;
    }
    std::size_t size() const { return count_; }
private:
    std::vector<T> data_;
    std::size_t head_ = 0, tail_ = 0, count_ = 0;
};

double eval_postfix(const std::string& expr) {               // e.g. "5 1 2 + 4 * + 3 -"
    Stack<double> st;
    std::istringstream in(expr);
    for (std::string tok; in >> tok;) {
        if (std::isdigit(static_cast<unsigned char>(tok[0]))) { st.push(std::stod(tok)); continue; }
        double b = st.pop(), a = st.pop();
        switch (tok[0]) {
            case '+': st.push(a + b); break;
            case '-': st.push(a - b); break;
            case '*': st.push(a * b); break;
            case '/': st.push(a / b); break;
            default: throw std::invalid_argument("unknown operator " + tok);
        }
    }
    double result = st.pop();
    if (!st.empty()) throw std::invalid_argument("too many operands");
    return result;
}

int main() {
    std::cout << "5 1 2 + 4 * + 3 -  = " << eval_postfix("5 1 2 + 4 * + 3 -") << '\n';
    std::cout << "15000 0.13 *  = " << eval_postfix("15000 0.13 *") << '\n';
    try {
        eval_postfix("1 +");
    } catch (const std::exception& e) {
        std::cout << "error: " << e.what() << '\n';
    }

    RingQueue<std::string> counter(3);
    for (const char* c : { "Asha", "Ravi", "Sita", "Hari" })
        std::cout << (counter.enqueue(c) ? "queued " : "queue full, turned away ") << c << '\n';
    std::cout << "served " << counter.dequeue() << '\n';
    counter.enqueue("Hari");                                  // reuses the freed slot (wrap-around)
    while (counter.size() > 0) std::cout << "served " << counter.dequeue() << '\n';
    return 0;
}

/* Output:
5 1 2 + 4 * + 3 -  = 14
15000 0.13 *  = 1950
error: pop from empty stack
queued Asha
queued Ravi
queued Sita
queue full, turned away Hari
served Asha
served Ravi
served Sita
served Hari
*/