Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

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.

BeginnerSTL Containers ProgramsExample 7 of 10
stack-basics.cpp
1#include <iostream>
2#include <stack>
3using namespace std;
4
5int main() {
6 // Create stack
7 stack<int> st;
8
9 // Push elements
10 st.push(10);
11 st.push(20);
12 st.push(30);
13 st.push(40);
14 st.push(50);
15
16 cout << "Stack size: " << st.size() << endl;
17 cout << "Top element: " << st.top() << endl;
18
19 // 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;
26
27 // Stack for string reversal
28 stack<char> charStack;
29 string str = "Hello";
30
31 cout << "\nOriginal string: " << str << endl;
32
33 // Push all characters
34 for (char c : str) {
35 charStack.push(c);
36 }
37
38 // Pop to reverse
39 string reversed = "";
40 while (!charStack.empty()) {
41 reversed += charStack.top();
42 charStack.pop();
43 }
44
45 cout << "Reversed string: " << reversed << endl;
46
47 // Check balanced parentheses
48 stack<char> parenStack;
49 string expression = "((()))";
50 bool balanced = true;
51
52 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 }
63
64 if (parenStack.empty() && balanced) {
65 cout << "\nExpression '" << expression << "' is balanced" << endl;
66 } else {
67 cout << "\nExpression '" << expression << "' is not balanced" << endl;
68 }
69
70 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. 1

    Push 10 to 50; size = 5, top = 50.

  2. 2

    Pop everything: 50 40 30 20 10.

  3. 3

    Push the letters of Hello and pop them: olleH.

  4. 4

    Scan ((())): push on (, pop on ).

  5. 5

    Stack empty and no early failure → balanced.

Dry run: Stack Basics

Parentheses "((()))":

  1. 1.( push → size 1
  2. 2.( push → size 2
  3. 3.( push → size 3
  4. 4.) pop → size 2
  5. 5.) pop → size 1
  6. 6.) pop → size 0
  7. 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:

Last In First Out
Last element added is first removed
Like a stack of plates
Only top element accessible

Key Features:

Simple operations
O(1) time complexity
Last-in-first-out order
Top element only accessible

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:

push(): adds element to top
pop(): removes top element
top(): returns top element (doesn't remove)
All O(1) operations

Stack Properties

Size and Empty:

st.size() // Number of elements

st.empty() // True if empty

Access:

Only top element accessible
Cannot access middle elements
Must pop to access lower elements
LIFO order enforced

String Reversal

Using Stack:

1.Push all characters to stack
2.Pop characters to reverse string

What happens here:

Push: "Hello" → stack: o, l, l, e, H (top)
Pop: "olleH" (reversed)
LIFO naturally reverses order

Balanced Parentheses

Algorithm:

1.Push '(' onto stack
2.Pop when ')' encountered
3.Balanced if stack empty at end

What happens here:

'(' pushes, ')' pops
Stack tracks nesting level
Empty stack = balanced
Non-empty = unbalanced

When to Use Stack

Good fits:

Expression evaluation
Balanced parentheses/braces
Function call simulation
Undo operations
Reverse order processing
Depth-first search (DFS)

Example Scenarios:

Calculator (postfix evaluation)
Syntax checking
Backtracking algorithms
Recursion simulation
Browser back button

Important Considerations

LIFO Order:

Last added = first removed
Cannot access arbitrary elements
Must pop to access lower elements
Natural for reverse processing

Performance:

All operations: O(1)
Very efficient
Simple implementation
Minimal overhead

Limitations:

Only top element accessible
Cannot search or access middle
Must pop to access other elements
Use other containers if random access needed

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.