Intermediate6 min readLesson 40 of 50
What is a Stack?
A stack is a LIFO (Last-In-First-Out) container. Elements are pushed and popped from the same end — the "top". Include <stack>.
#include <iostream>
#include <stack>
using namespace std;
int main() {
stack<int> s;
s.push(10);
s.push(20);
s.push(30);
cout << "Top: " << s.top() << endl; // 30
cout << "Size: " << s.size() << endl; // 3
while (!s.empty()) {
cout << s.top() << " ";
s.pop();
}
cout << endl;
return 0;
}
Output:
Top: 30
Size: 3
30 20 10
Real-World Use Cases
- Undo/Redo in text editors
- Browser back button (page history)
- Function call stack in program execution
- Expression evaluation (balanced parentheses, RPN)
// Check balanced parentheses using a stack
string expr = "{[()]}";
stack<char> st;
bool balanced = true;
for (char c : expr) {
if (c=='(' || c=='[' || c=='{') {
st.push(c);
} else {
if (st.empty()) { balanced = false; break; }
char top = st.top(); st.pop();
if ((c==')' && top!='(') || (c==']' && top!='[') || (c=='}' && top!='{'))
{ balanced = false; break; }
}
}
if (!st.empty()) balanced = false;
cout << (balanced ? "Balanced" : "Not balanced") << endl; // Balanced
Exercise
Use a stack to reverse a string. Push each character onto a stack, then pop them off to form the reversed string.
Show Solution
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main() {
string input = "Hello, World!";
stack<char> s;
for (char c : input) s.push(c);
string reversed = "";
while (!s.empty()) { reversed += s.top(); s.pop(); }
cout << reversed << endl; // !dlroW ,olleH
return 0;
}
Quiz
What does LIFO mean?
- A) Last In, Fast Out
- B) Last In, First Out
- C) Linear In, First Out
- D) List In, Final Out
Answer
B) Last In, First Out
Summary
stack is LIFO: push and pop from the top.- Methods:
push, pop, top, empty, size. - Classic use cases: undo, browser history, expression parsing.