CHAPTER 23
Beginner
Stack and Queue Implementation
Updated: May 17, 2026
5 min read
# CHAPTER 23
Stack and Queue Implementation
1. Introduction
Stacks and Queues are abstract data structures that dictate *how* data is added and removed. A Stack works like a stack of plates at a buffet. A Queue works like a line of people at a movie theater. In this chapter, we will implement both using Arrays in C.2. Learning Objectives
By the end of this chapter, you will be able to:- Explain the LIFO principle of a Stack.
- Implement Stack operations: push, pop, peek.
- Explain the FIFO principle of a Queue.
- Implement Queue operations: enqueue, dequeue.
- Understand Overflow and Underflow conditions.
3. Stack (LIFO - Last In, First Out)
The last item placed on the stack is the first one removed.- Push: Add an item to the top.
- Pop: Remove an item from the top.
- Peek/Top: Look at the top item without removing it.
c
4. Visualizing a Stack
5. Queue (FIFO - First In, First Out)
The first item placed in the queue is the first one removed.- Enqueue: Add an item to the rear (back).
- Dequeue: Remove an item from the front.
c
6. Visualizing a Queue
*(Note: A basic array queue wastes space as front moves forward. A "Circular Queue" solves this by wrapping around).*
7. Real-World Applications
- Stacks: The Call Stack (functions), Undo features in text editors, Browser back buttons, balancing parentheses in compilers.
- Queues: Printer job scheduling, CPU task scheduling, waiting lines in web servers, BFS (Breadth-First Search) algorithms.
8. Common Mistakes
-
Stack Overflow: Trying to
pushwhentop == MAX - 1.
-
Stack Underflow: Trying to
popwhentop == -1.
- Queue Memory Waste: In a linear array queue, dequeuing doesn't shift elements, so the front spaces become unusable. (Fix: Use a Circular Queue or Linked List).
9. Exercises
-
1.
Add a
peek()function to the Stack code that returns the top element without popping it.
-
2.
Add a
display()function to the Queue code that prints all current elements fromfronttorear.
10. MCQ Quiz with Answers
Question 1
A Stack follows which principle?
Question 2
A Queue follows which principle?
Question 3
What is it called when you try to Pop from an empty stack?
Question 4
Where are elements added in a Queue?
Question 5
Where are elements removed from in a Queue?
Question 6
What does top start at in an empty array-based stack?
Question 7
Which operation looks at the top of the stack without removing it?
Question 8
The Undo function in Microsoft Word uses which data structure?
Question 9
Print jobs sent to a printer use which data structure?
Question 10
What is a limitation of a simple array-based Queue?
11. Interview Questions
- Q: How would you implement a Queue using two Stacks?
- Q: What is a Circular Queue, and how does it solve the memory waste problem of a linear array queue?
- Q: Explain how the OS uses a Stack for function calls.