A pile of plates
A stack only lets you touch the top. The last thing in is the first thing out: LIFO.
Think of it like this: A stack of plates. Your browser's Back button and an editor's Undo work the same way.
| Operation | std::stack | Big-O |
|---|---|---|
| push on top | s.push(x) | O(1) |
| remove top | s.pop() | O(1) |
| look at top | s.top() | O(1) |
| is it empty? | s.empty() | O(1) |
#include <iostream>
#include <stack>
#include <string>
using namespace std;
bool balanced(const string& text) {
stack<char> s;
for (char ch : text) {
if (ch == '(' || ch == '[' || ch == '{') s.push(ch);
else if (ch == ')' || ch == ']' || ch == '}') {
char want = ch == ')' ? '(' : ch == ']' ? '[' : '{';
if (s.empty() || s.top() != want) return false;
s.pop();
}
}
return s.empty();
}
int main() {
for (string t : {"{[()()]}", "([)]", "((", "f(a[0])"})
cout << t << " " << (balanced(t) ? "balanced" : "not balanced") << endl;
return 0;
}Output
{[()()]} balanced
([)] not balanced
(( not balanced
f(a[0]) balancedCommon mistake:
s.pop()returns nothing in C++ – reads.top()first. And never calltop()orpop()on an empty stack: it's undefined behaviour (often a crash).