Stack Operations


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.

{ "array": ["10", "20", "30", " "], "emptyIndices": [3, 4], "highlightIndices": [] }

 Initial Stack

{ "array": ["10", "20", "30", "40", "↓"], "emptyIndices": [4], "highlightIndicesGreen": [3] }

 Push 40 onto the stack

{ "array": ["10", "20", "30", "40", " "], "emptyIndices": [4] }

 Updated Stack

2. Pop

The pop operation removes the top element from the stack.

{ "array": ["10", "20", "30", "40", ""], "emptyIndices": [4], "highlightIndices": [] }

 Initial Stack

{ "array": ["10", "20", "30", "40", "↑"], "emptyIndices": [4], "highlightIndicesRed": [3] }

 Pop 40 from the stack

{ "array": ["10", "20", "30", ""], "emptyIndices": [3] }

 Updated Stack

3. Peek

The peek operation returns the top element of the stack without removing it.

Current Stack:

{ "array": [10, 20, 30], "highlightIndices": [2] }

Peek Result: 30

4. isEmpty

The isEmpty operation checks whether the stack has any elements.

Stack with elements:

{ "array": [10, 20, 30], "highlightIndices": [] }

isEmpty Result: false

Empty Stack:

{ "array": [""], "emptyIndices": [0], "highlightIndices": [] }

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)

{ "array": [10, 20, 30], "highlightIndices": [2] }

Next Element (index 1)

{ "array": [10, 20, 30], "highlightIndices": [1] }

Bottom Element (index 0)

{ "array": [10, 20, 30], "highlightIndices": [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.