Stack Basics in C++
C++ stack basics with LIFO order: push, top, pop, size, and empty, plus two classic uses: reversing a string and checking balanced parentheses, with output.
1#include <iostream>2#include <stack>3using namespace std;45int main() {6 // Create stack7 stack<int> st;89 // Push elements10 st.push(10);11 st.push(20);12 st.push(30);13 st.push(40);14 st.push(50);1516 cout << "Stack size: " << st.size() << endl;17 cout << "Top element: " << st.top() << endl;1819 // Display stack (by popping)20 cout << "\nStack elements (LIFO - Last In First Out):" << endl;21 while (!st.empty()) {22 cout << st.top() << " ";23 st.pop();24 }25 cout << endl;2627 // Stack for string reversal28 stack<char> charStack;29 string str = "Hello";3031 cout << "\nOriginal string: " << str << endl;3233 // Push all characters34 for (char c : str) {35 charStack.push(c);36 }3738 // Pop to reverse39 string reversed = "";40 while (!charStack.empty()) {41 reversed += charStack.top();42 charStack.pop();43 }4445 cout << "Reversed string: " << reversed << endl;4647 // Check balanced parentheses48 stack<char> parenStack;49 string expression = "((()))";50 bool balanced = true;5152 for (char c : expression) {53 if (c == '(') {54 parenStack.push(c);55 } else if (c == ')') {56 if (parenStack.empty()) {57 balanced = false;58 break;59 }60 parenStack.pop();61 }62 }6364 if (parenStack.empty() && balanced) {65 cout << "\nExpression '" << expression << "' is balanced" << endl;66 } else {67 cout << "\nExpression '" << expression << "' is not balanced" << endl;68 }6970 return 0;71}
Sample Output
50 40 30 20 10
Popped in reverse push order.
Reversed string: olleH
The last character pushed comes out first.
In this one
- What LIFO order means
- Why you call top() before pop()
- How a stack reverses a sequence
- How to check balanced parentheses
How it works
- 1
Push 10 to 50; size = 5, top = 50.
- 2
Pop everything: 50 40 30 20 10.
- 3
Push the letters of Hello and pop them: olleH.
- 4
Scan ((())): push on (, pop on ).
- 5
Stack empty and no early failure → balanced.
Dry run: Stack Basics
Parentheses "((()))":
- 1.( push → size 1
- 2.( push → size 2
- 3.( push → size 3
- 4.) pop → size 2
- 5.) pop → size 1
- 6.) pop → size 0
- 7.End: empty and balanced = true
Parentheses "((()))": ( push → size 1 ( push → size 2 ( push → size 3 ) pop → size 2 ) pop → size 1 ) pop → size 0 End: empty and balanced = true
Edge cases
top() on an empty stack
Call st.top() after the display loop.
The stack is empty, so this is undefined behavior. Check empty() first.
Unbalanced input
Try "(()" and "())".
"(()" leaves one item on the stack. "())" tries to pop an empty stack, so balanced is set to false and the loop breaks.
What's going on
A stack lets you add and remove at one end only, the top. The last item pushed is the first one popped, which is called LIFO (last in, first out). Think of a stack of plates.
stack<int> st; and five push calls put 10 to 50 on the stack, with 50 on top. size() is 5 and top() is 50.
There is no way to loop over a stack; it hides everything except the top. So the display loop reads top(), then calls pop() to remove it, until empty() is true. The numbers come out reversed: 50 40 30 20 10. Note that pop() returns nothing. You read with top() first, then pop.
The second part uses that reversal on a string. Each character of "Hello" is pushed, then popped into reversed, giving "olleH".
The third part is the classic stack problem: checking parentheses. Each ( is pushed. Each ) must match an open one, so the code pops; if the stack is already empty, there is a ) with nothing to close and balanced becomes false. At the end, the expression is balanced only if no ) failed and the stack is empty, meaning every ( was closed. "((()))" passes. "(()" would leave one ( on the stack, and "())" would hit an empty stack.
All stack operations are O(1). Under the hood, stack is an adapter around a deque by default.
The headers come first. <iostream> is there because it provides cout and cin for input/output operations. <stack> is there because it provides stack container class. Leave one out and the compiler stops at the first name it does not recognize.
Understanding Stack
LIFO Concept:
Key Features:
Stack Operations
push():
st.push(10); // Add to top
pop():
st.pop(); // Remove from top
top():
int value = st.top(); // Access top element
What happens here:
Stack Properties
Size and Empty:
st.size() // Number of elements
st.empty() // True if empty
Access:
String Reversal
Using Stack:
What happens here:
Balanced Parentheses
Algorithm:
What happens here:
When to Use Stack
Good fits:
Example Scenarios:
Important Considerations
LIFO Order:
Performance:
Limitations:
return 0;
return 0; closes main and tells the operating system the program finished without an error.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Push 1, 2, 3, then pop once. What is top()?
Pick an answer to check it.
Question 2
Why is "())" not balanced?
Pick an answer to check it.
Questions people ask
Why doesn't pop() return the value?
Returning by value could throw while copying, after the element was already removed. Splitting top and pop avoids losing data.
How would I check [], {}, and () together?
Push each opening bracket, and on a closer check that the top is the matching opener before popping.
What else are stacks used for?
Undo history, expression evaluation, and depth-first search.