👁 Preview — Study, Practice and Revise are open; mock tests and the rest of the syllabus unlock on subscription. Unlock all · ₹4,999
← Back to Linear Data Structures
Study mode

Stacks

Introduction to Stacks

Imagine a stack of plates in your kitchen. You place plates one on top of another, forming a neat pile. When you need a plate, you take the one from the top. You cannot take a plate from the middle or bottom without disturbing the ones above it. This simple idea forms the basis of a stack in computer science.

A stack is a linear data structure that follows the Last In, First Out (LIFO) principle. This means the last element added (pushed) to the stack is the first one to be removed (popped). Stacks are essential in many computing tasks such as expression evaluation, undo mechanisms in software, and managing function calls.

Bottom Plate Top Plate Last In First Out

Stack Operations

Stacks support a few fundamental operations that allow us to add, remove, and inspect elements:

  • Push: Add an element to the top of the stack.
  • Pop: Remove the top element from the stack.
  • Peek/Top: View the top element without removing it.
  • IsEmpty: Check if the stack has no elements.
  • IsFull: Check if the stack has reached its maximum capacity (relevant in fixed-size stacks).
graph TD    A[Start] --> B{Is stack full?}    B -- No --> C[Push element]    C --> D[Update top pointer]    D --> E[End]    B -- Yes --> F[Stack Overflow Error]    A --> G{Is stack empty?}    G -- No --> H[Pop element]    H --> I[Update top pointer]    I --> E    G -- Yes --> J[Stack Underflow Error]

Stack Implementation Using Arrays

An array is a collection of elements stored in contiguous memory locations. We can use an array to implement a stack by maintaining a variable called top that points to the current top element in the stack.

Initially, when the stack is empty, top = -1. When we push an element, we increment top and place the new element at array[top]. When popping, we remove the element at array[top] and decrement top.

However, since arrays have fixed size, we must check for overflow (when top == size - 1) before pushing, and underflow (when top == -1) before popping.

10 20 30 Index 0 Index 1 Index 2 Index 3 Index 4 Index 5 top

Stack Implementation Using Linked Lists

A linked list is a collection of nodes where each node contains data and a reference (or pointer) to the next node. Unlike arrays, linked lists allow dynamic memory allocation, so the stack can grow or shrink as needed without worrying about fixed size.

In a linked list-based stack, the top pointer points to the head node. Push operation adds a new node at the head, and pop removes the node from the head. This makes both operations efficient with time complexity \(O(1)\).

30 20 10 top

Worked Examples

Example 1: Evaluating a Postfix Expression Using Stack Medium
Evaluate the postfix expression 5 6 2 + * 12 4 / - using a stack.

Step 1: Initialize an empty stack.

Step 2: Read the expression from left to right.

Step 3: Push operands onto the stack.

Step 4: When an operator is encountered, pop the top two operands, apply the operator, and push the result back.

Step 5: Process each token:

  • Push 5 -> Stack: [5]
  • Push 6 -> Stack: [5, 6]
  • Push 2 -> Stack: [5, 6, 2]
  • Operator '+': Pop 2 and 6 -> 6 + 2 = 8 -> Push 8 -> Stack: [5, 8]
  • Operator '*': Pop 8 and 5 -> 5 * 8 = 40 -> Push 40 -> Stack: [40]
  • Push 12 -> Stack: [40, 12]
  • Push 4 -> Stack: [40, 12, 4]
  • Operator '/': Pop 4 and 12 -> 12 / 4 = 3 -> Push 3 -> Stack: [40, 3]
  • Operator '-': Pop 3 and 40 -> 40 - 3 = 37 -> Push 37 -> Stack: [37]

Answer: The value of the postfix expression is 37.

Example 2: Implementing Stack Operations Using Array Easy
Perform the following operations on an empty stack of size 5 implemented using an array: push 10, push 20, pop, push 30, push 40, push 50, push 60.

Step 1: Initialize top = -1 and array size = 5.

Step 2: Push 10 -> top = 0, stack = [10]

Step 3: Push 20 -> top = 1, stack = [10, 20]

Step 4: Pop -> remove 20, top = 0, stack = [10]

Step 5: Push 30 -> top = 1, stack = [10, 30]

Step 6: Push 40 -> top = 2, stack = [10, 30, 40]

Step 7: Push 50 -> top = 3, stack = [10, 30, 40, 50]

Step 8: Push 60 -> top = 4, stack = [10, 30, 40, 50, 60]

Step 9: Attempt to push another element would cause stack overflow since top = size - 1.

Answer: Final stack contents: [10, 30, 40, 50, 60]

Example 3: Detecting Balanced Parentheses Using Stack Medium
Check if the expression {[()()]} has balanced parentheses using a stack.

Step 1: Initialize an empty stack.

Step 2: Traverse the expression character by character:

  • '{' -> push -> Stack: ['{']
  • '[' -> push -> Stack: ['{', '[']
  • '(' -> push -> Stack: ['{', '[', '(']
  • ')' -> pop -> matches '(' -> Stack: ['{', '[']
  • '(' -> push -> Stack: ['{', '[', '(']
  • ')' -> pop -> matches '(' -> Stack: ['{', '[']
  • ']' -> pop -> matches '[' -> Stack: ['{']
  • '}' -> pop -> matches '{' -> Stack: []

Step 3: Stack is empty at the end, so parentheses are balanced.

Answer: The expression is balanced.

Example 4: Converting Infix to Postfix Expression Hard
Convert the infix expression (A + B) * (C - D) to postfix using stack operations.

Step 1: Initialize an empty stack for operators and an empty output string.

Step 2: Scan the expression from left to right:

  • '(' -> push to stack -> Stack: ['(']
  • 'A' -> add to output -> Output: "A"
  • '+' -> push to stack -> Stack: ['(', '+']
  • 'B' -> add to output -> Output: "AB"
  • ')' -> pop operators until '(' -> pop '+' -> Output: "AB+"; pop '(' and discard -> Stack: []
  • '*' -> push to stack -> Stack: ['*']
  • '(' -> push to stack -> Stack: ['*', '(']
  • 'C' -> add to output -> Output: "AB+C"
  • '-' -> push to stack -> Stack: ['*', '(', '-']
  • 'D' -> add to output -> Output: "AB+CD"
  • ')' -> pop until '(' -> pop '-' -> Output: "AB+CD-"; pop '(' -> Stack: ['*']

Step 3: Pop remaining operators -> pop '*' -> Output: "AB+CD-*"

Answer: The postfix expression is AB+CD-*.

Example 5: Stack Overflow and Underflow Scenarios Easy
Explain stack overflow and underflow with examples in an array-based stack of size 3.

Stack Overflow: Occurs when trying to push an element into a full stack.

Example: Stack size = 3, current elements = [10, 20, 30], top = 2.

Attempt to push 40 -> Since top = size - 1, no space left -> Overflow error.

Stack Underflow: Occurs when trying to pop an element from an empty stack.

Example: Stack is empty, top = -1.

Attempt to pop -> No elements to remove -> Underflow error.

Answer: Always check stack boundaries before push/pop to avoid these errors.

Formula Bank

Maximum Stack Size
\[ \text{Size} = n \]
where: \( n \) = size of the array

Tips & Tricks

Tip: Remember the LIFO principle by imagining a stack of plates where you can only add or remove the top plate.

When to use: When trying to understand or explain stack behavior quickly.

Tip: Use a single pointer top to track the current element in array-based stacks to simplify push and pop operations.

When to use: During implementation of stack using arrays.

Tip: For balanced parentheses problems, push opening brackets and pop when encountering closing brackets; if mismatch or stack empty, expression is unbalanced.

When to use: When solving syntax checking problems in expressions.

Tip: In expression evaluation, always push operands and pop two operands when an operator is encountered to apply the operation.

When to use: While evaluating postfix or prefix expressions.

Tip: To avoid stack overflow in array implementation, always check if top has reached the maximum size before pushing.

When to use: When performing push operations in static stacks.

Common Mistakes to Avoid

❌ Confusing stack with queue and applying FIFO logic instead of LIFO.
✓ Always remember stack follows LIFO; the last element pushed is the first popped.
Why: Students often mix up linear data structures due to similar terminology.
❌ Not checking for stack overflow or underflow before push or pop operations.
✓ Implement boundary checks to prevent invalid operations.
Why: Leads to runtime errors and incorrect program behavior.
❌ Incorrectly updating the top pointer during push and pop operations.
✓ Increment top after push and decrement before pop consistently.
Why: Mismanagement of top causes data corruption or access errors.
❌ Forgetting to handle empty stack cases when performing peek/top operation.
✓ Always check if stack is empty before accessing top element.
Why: Accessing top of empty stack causes errors.
❌ Mixing up operator precedence while converting infix to postfix expressions.
✓ Use a precedence table and stack to correctly order operators.
Why: Incorrect precedence leads to wrong expression evaluation.
FeatureStackQueueDeque
OrderLIFO (Last In First Out)FIFO (First In First Out)Both ends insertion/removal
Insertion/RemovalTop onlyFront removal, rear insertionFront and rear
Use CasesExpression evaluation, backtrackingScheduling, buffering Yes
Overflow HandlingCheck top pointerCheck front and rear pointersCheck front and rear pointers
Curated videos per subtopic
Top YouTube explainers, AI-ranked for your exam and language. Unlocks with subscription.
Unlock

Try Practice next.

Progress tracking is paywalled — subscribe to mark subtopics as understood and save your streak.

Go to practice →
Ask a doubt
Stacks · 10 free messages
Ask me anything about this subtopic. You have 10 free messages this session — chat history isn't saved in preview.