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(), andpeek().
- 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.
push(data): Places a new element onto the top of the Stack.
-
2.
pop(): Removes and returns the element currently at the top of the Stack.
-
3.
peek()(ortop()): Looks at the top element without actually removing it.
-
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 calledtop to track the current index.
c
5. Implementation 2: Linked List-Based Stack
The fatal flaw of the Array-based Stack is theStack 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
6. Complexity Analysis
Because we strictly interact with the very Top (Indextop in Arrays, or the Head in Linked Lists), there are absolutely no loops involved!
| Operation | Time Complexity |
|---|---|
| Push | O(1) |
| Pop | O(1) |
| Peek | O(1) |
7. Real-World Applications
Why do we restrict ourselves to LIFO logic?-
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 systempop()s the most recent word and deletes it.
-
2.
Compiler Syntax Checking: How does the compiler know if your
{ [ ( ) ] }brackets are perfectly balanced? It uses a Stack!
- 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
9. Common Mistakes
-
Stack Underflow: Calling
pop()on an empty stack. If you don't wrap yourpop()function in anif (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'slist, or C++std::stack. They are heavily optimized by compiler engineers.
11. Exercises
-
1.
Trace the operations on paper:
push(5),push(10),pop(),push(20),peek(). What is the value returned bypeek()?
- 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
MinStackclass that supportspush(),pop(),top(), and retrieving the minimum element in constantO(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 stackisEmpty(). 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.