Stacks and Queues
Stack Push/Pop
Push values onto a stack and pop them back in last-in, first-out order.
Algorithm
Basic Implementation
basic.cpp
#include <deque>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
string render(const vector<int>& values) {
ostringstream out;
for (size_t i = 0; i < values.size(); ++i) {
if (i > 0) out << " -> ";
out << values[i];
}
return out.str();
}
int main() {
vector<int> stack;
for (int value : {10, 20, 30}) stack.push_back(value);
vector<int> popped;
while (!stack.empty()) {
popped.push_back(stack.back());
stack.pop_back();
}
cout << render(popped) << endl;
}
Complexity
- Time: O(1) per push/pop
- Space: O(n)
Implementation notes
- In C++, the checked source uses
std::vector<int> stackas the stack backing store; it does not use thestd::stackadapter. - Push uses
stack.push_back(value)over{10, 20, 30}. The logical top is the vector back, so pop readsstack.back()beforestack.pop_back(). - The pop loop is guarded by
while (!stack.empty()), soback()andpop_back()are only called on a non-empty vector in the checked path. - Popped integers are copied into
std::vector<int> popped; there is no ownership transfer or reference aliasing between the vectors. - The trace records stack
[], then[10, 20, 30], then popped[30]with stack[10, 20], ending with popped[30, 20, 10]and stack[]. render(const std::vector<int>&)usesstd::ostringstreamand asize_tloop to produce30 -> 20 -> 10, which is printed withstd::cout.- Visible allocation is the stack vector, popped vector, and output string
buffer; mutation happens through vector
push_backandpop_back.
top
The top is the most recently pushed value.
LIFO
A stack removes values in last-in, first-out order.