01
Module 5: Stack Data Structure
A stack is a linear data structure where insertion and removal happen at the same end, called the top. It follows Last-In, First-Out (LIFO) order.
This means the last item placed into the stack is the first item removed.
A common real-world example is a stack of plates. The newest plate placed on top is usually the first one taken off.
Basic Stack Operations
| Operation | Description |
|---|---|
push | Adds an item to the top of the stack. |
pop | Removes and returns the top item. |
peek / top | Returns the top item without removing it. |
isEmpty | Checks whether the stack contains no items. |
Overflow and Underflow
- Overflow happens when an item is pushed into a stack that has no more available space.
- Underflow happens when a pop operation is attempted on an empty stack.
In Java, built-in dynamic collections can grow as needed, but the concepts still matter when stacks are implemented with fixed-size arrays.
Java Stack lastElement()
In Java, a Stack object can use lastElement() to retrieve the item at the last index of the stack's internal list.
Syntax:
stack.lastElement();
This returns a value but does not remove it.
02
Activity 6: Stack Simulation
03