Skip to main content
Data Structures
CHAPTER 11 Beginner

Stack Data Structure

Updated: May 17, 2026
15 min read

# CHAPTER 11

Stack Data Structure

1. Introduction

Imagine you are at a buffet and there is a tall stack of clean plates. The dishwasher brings a new plate and places it directly on *top* of the stack. When you arrive to get food, you take the plate that is sitting on the *top* of the stack. You cannot pull a plate from the very bottom, or the entire tower will crash. This physical constraint is the exact definition of a Stack Data Structure. A Stack is an Abstract Data Type (ADT) defined by one strict architectural rule: LIFO (Last In, First Out). The last item placed into the system is mathematically guaranteed to be the first item removed.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Define the LIFO principle.
  • Execute the three core Stack operations: push(), pop(), and peek().
  • Implement a Stack using both Arrays and Linked Lists.
  • Analyze the Time and Space Complexity of Stack operations.
  • Build a real-world "Undo" mechanism.

3. The Core Operations

A Stack strictly prohibits random access. You cannot ask for the "3rd item". You only have access to the absolute top of the tower.
  1. 1. push(data): Places a new element onto the top of the Stack.
  1. 2. pop(): Removes and returns the element currently at the top of the Stack.
  1. 3. peek() (or top()): Looks at the top element without actually removing it.
  1. 4. isEmpty(): Returns True if the Stack has zero elements.

4. Implementation 1: Array-Based Stack

Because a Stack is just an abstract concept (a set of rules), we have to build it using physical memory (like an Array). We use an integer variable called top to track the current index.
c
12345678910111213141516171819202122232425
// C Example: Building a Stack using a static Array
#include <stdio.h>
#define MAX 100

int stack[MAX];
int top = -1; // -1 means the stack is totally empty!

void push(int data) {
    if (top >= MAX - 1) {
        printf("Stack Overflow! The array is completely full.\n");
        return;
    }
    top++; // Move the pointer up
    stack[top] = data; // Drop the data in
}

int pop() {
    if (top < 0) {
        printf("Stack Underflow! Nothing to pop.\n");
        return -1;
    }
    int popped_data = stack[top];
    top--; // Move the pointer down (the data is overwritten later)
    return popped_data;
}

5. Implementation 2: Linked List-Based Stack

The fatal flaw of the Array-based Stack is the Stack Overflow. If MAX is 100, you cannot push 101 items. If we build the Stack using a Singly Linked List, it can grow infinitely! We simply treat the Head of the Linked List as the "Top" of the stack.
java
1234567891011121314151617181920212223242526
// Java Example: Building a Stack using a Linked List
class Node {
    int data;
    Node next;
    public Node(int d) { data = d; next = null; }
}

public class CustomStack {
    Node top = null; // The Head of the list

    public void push(int data) {
        Node newNode = new Node(data);
        newNode.next = top; // New node points to old top
        top = newNode; // New node becomes the absolute top
    }

    public int pop() {
        if (top == null) {
            System.out.println("Stack Underflow!");
            return -1;
        }
        int poppedData = top.data;
        top = top.next; // Top pointer drops down to the next node!
        return poppedData;
    }
}

6. Complexity Analysis

Because we strictly interact with the very Top (Index top in Arrays, or the Head in Linked Lists), there are absolutely no loops involved!
OperationTime Complexity
PushO(1)
PopO(1)
PeekO(1)
*Stacks are mathematically perfect structures providing instantaneous performance.*

7. Real-World Applications

Why do we restrict ourselves to LIFO logic?
  1. 1. The Undo Button: (Ctrl+Z). Every time you type a word in MS Word, it is push()ed to a Stack. When you press Undo, the system pop()s the most recent word and deletes it.
  1. 2. Compiler Syntax Checking: How does the compiler know if your { [ ( ) ] } brackets are perfectly balanced? It uses a Stack!
  1. 3. The OS Call Stack: As discussed in Chapter 6, computers use Stacks natively in RAM to manage recursive function calls.

8. Mini Project: Balancing Parentheses

This is the ultimate Stack interview question. Determine if { [ ( ) ] } is valid, and if { [ ( ] ) } is invalid.
python
12345678910111213141516171819202122
# Python Example: Parentheses Checker using a List as a Stack
def is_balanced(expression):
    stack = [] # Python lists have native O(1) push (append) and pop
    brackets = {&#039;)': '(', '}': '{', ']': '['} # Hash map for fast lookup
    
    for char in expression:
        if char in [&#039;(', '{', '[']:
            stack.append(char) # PUSH opening brackets
        elif char in [&#039;)', '}', ']']:
            if len(stack) == 0:
                return False # Underflow! More closing than opening.
                
            top_element = stack.pop() # POP the last opened bracket
            
            # Check for a mismatch
            if brackets[char] != top_element:
                return False
                
    # If the stack is empty at the end, it's perfectly balanced!
    return len(stack) == 0

print(is_balanced("{[()]}")) # True

9. Common Mistakes

  • Stack Underflow: Calling pop() on an empty stack. If you don't wrap your pop() function in an if (isEmpty()) check, attempting to extract data from a negative array index or a NULL pointer will violently crash your software.

10. Best Practices

  • Use Standard Libraries: In modern programming, never write a Stack from scratch unless you are in an interview. Use java.util.Stack, Python's list, or C++ std::stack. They are heavily optimized by compiler engineers.

11. Exercises

  1. 1. Trace the operations on paper: push(5), push(10), pop(), push(20), peek(). What is the value returned by peek()?
  1. 2. Write a function that uses a Stack to reverse a String. *(Hint: Push every character into the stack, then Pop them all out! Because of LIFO, they will come out backward!).*

12. MCQs with Answers

Question 1

What is the defining architectural principle of a Stack data structure?

Question 2

When a program attempts to execute the pop() operation on a Stack that contains absolutely zero elements, what specific software error occurs?

Question 3

If an Array-based Stack of maximum size 10 is currently completely full, and the application attempts to execute push(99), what error occurs?

Question 4

What is the Time Complexity for successfully executing push() or pop() on a properly engineered Stack?

Question 5

When implementing a Stack utilizing a Singly Linked List architecture, which specific end of the Linked List represents the "Top" of the Stack to ensure O(1) Time Complexity?

Question 6

The peek() (or top()) operation performs what exact function?

Question 7

Which ubiquitous computer software feature relies fundamentally on a Stack structure to operate correctly?

Question 8

How does a compiler utilize a Stack to verify if mathematical parentheses e.g., ( [ { } ] ) are perfectly balanced?

Question 9

If a developer implements a Stack using an Array, what happens to the physical data located at stack[top] immediately after pop() is called and the top integer is decremented?

Question 10

Why is pushing elements into a Stack, and immediately popping all of them back out, a common technique in computer science?

13. Interview Preparation

Top Interview Questions:
  • *Algorithmic Coding:* "Implement a MinStack class that supports push(), pop(), top(), and retrieving the minimum element in constant O(1) time." *(Hint: You must maintain TWO stacks simultaneously. One for normal data, and one strictly tracking the current minimum value).*
  • *System Design:* "Design a Stack capable of infinite growth utilizing a raw Array structure. Explain the internal resizing logic." *(Answer: It's essentially implementing a Dynamic Array under the hood!).*

Common Pitfalls:

  • Calling pop() inside a loop without checking if the stack isEmpty(). If the logic iterates one too many times, the Underflow Exception will result in an immediate whiteboard failure.

14. FAQs

Q: Why would I use a Stack when an Array can do the same thing and more? A: Safety and Encapsulation. An Array lets a junior developer overwrite index [5], destroying data integrity. A Stack physically blocks developers from touching anything except the Top, guaranteeing that complex state logic (like Undo chains or function calls) cannot be corrupted.

15. Summary

The Stack is an Abstract Data Type ruled by LIFO math. By purposefully restricting access to only the topmost element, Stacks guarantee flawless O(1) performance and provide the mathematical framework required to process recursive state tracking, compiler parsing, and browser navigation.

16. Next Chapter Recommendation

The Stack handles "Last In, First Out". But what if we want fairness? If 50 people are waiting to buy concert tickets, the last person to arrive should absolutely not get their ticket first! In Chapter 12: Queue Data Structure, we will architect the FIFO principle to handle fair scheduling systems.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·