What is Overflow & Underflow (in Stack/Queue)?
I will explain Overflow and Underflow in the context of Stack and Queue in detail.
What are Overflow and Underflow?
These are both conditions that occur in a Data Structure (like Stack or Queue) when you perform an operation (such as inserting or removing data), but that operation violates the rules or capacity at that time.
Overflow and Underflow in Stack
Stack is a LIFO (Last-In, First-Out) Data Structure, which works like a stack of plates. Data insertion (Push) and data removal (Pop) happen only from one end, called the Top.
1. Stack Overflow
- What happens? When you try to insert more data (element) into a full Stack (Push).
- Why does it happen? Every Stack has a fixed size or maximum capacity. When the Stack already contains as many elements as it can hold, and you try to insert one more element, it results in Overflow.
- In simple terms: Like if you have space for only 10 plates and you try to place the 11th plate on top, it will fall off.
2. Stack Underflow
- What happens? When you try to remove data (element) from an empty Stack (Pop).
- Why does it happen? When there is no element in the Stack at all (meaning the Top pointer is at
-1), and you want to fetch an element by Popping it. - In simple terms: Like if the stack of plates is already empty, and you try to remove a plate from it, you won't be able to remove anything.
Overflow and Underflow in Queue
Queue is a FIFO (First-In, First-Out) Data Structure, which works like a line (queue). Data is inserted from one end called Rear or Tail, and removed from the other end called Front or Head.
1. Queue Overflow
- What happens? When you try to insert more data (element) into a full Queue (Enqueue).
- Why does it happen? Like Stack, Queue also has a fixed size. When the Rear pointer reaches its maximum limit, and you try to Enqueue one more element, it results in Overflow condition.
- In simple terms: Like if only 50 people can stand in the movie ticket line, and the 51st person tries to join the line.
2. Queue Underflow
- What happens? When you try to remove data (element) from an empty Queue (Dequeue).
- Why does it happen? When there is no element in the Queue at all (meaning the Front and Rear pointers are in wrong positions, like
Front = Rear = -1), and you want to remove an element by Dequeueing it. - In simple terms: Like if the ATM line is empty, and you ask someone to come out of it.
Main Difference
| Feature | Stack (Push/Pop) | Queue (Enqueue/Dequeue) |
|---|---|---|
| Overflow | Performing Push on a full Stack | Performing Enqueue on a full Queue |
| Underflow | Performing Pop on an empty Stack | Performing Dequeue on an empty Queue |
Both these conditions are very important in programming for Error Handling (handling errors) so that your program does not crash.
Would you like to know the working steps of Push and Pop operations in Stack?
Comments
Post a Comment