Stacks support a core set of operations that are fundamental to their Last-In First-Out (LIFO) behavior. In this section, we explore the essential operations — Push, Pop, Peek, isEmpty, and Traversal — using visual step-by-step diagrams.
1. Push
The push operation adds a new element to the top of the stack.
Initial Stack
Push 40 onto the stack
Updated Stack
2. Pop
The pop operation removes the top element from the stack.
Initial Stack
Pop 40 from the stack
Updated Stack
3. Peek
The peek operation returns the top element of the stack without removing it.
Current Stack:
Peek Result: 30
4. isEmpty
The isEmpty operation checks whether the stack has any elements.
Stack with elements:
isEmpty Result: false
Empty Stack:
isEmpty Result: true
5. Traversal
Traversal visits all elements from the top of the stack to the bottom.
Start Traversal (Top → Bottom):
Top Element (index 2)
Next Element (index 1)
Bottom Element (index 0)
Traversal Complete.
While a stack traditionally allows access only to the top element through operations like push, pop, and peek, it is possible to traverse a stack from top to bottom without popping elements — but only if you have direct access to the underlying data structure. In many practical implementations, stacks are built using arrays or lists, which means elements can be accessed by index. This makes it easy to visualize or iterate over the stack elements from top to bottom in a read-only manner without modifying the actual stack content.
However, in strictly abstract stack implementations where index-based access isn't available (such as with LifoQueue in Python or using interfaces in some languages), the only way to traverse would be by repeatedly popping each element, which alters the stack. To maintain the original state, you'd need to store the popped elements in a temporary structure and rebuild the stack afterward.
For visualization or learning purposes, though, accessing by index is perfectly acceptable and often more intuitive.