Skip to content

Computer Science · Ch 3 — Stack

PUSH and POP Operations

3.3.1

PUSH and POP Operations

The two fundamental operations on a stack are PUSH and POP. They are the only ways to insert or remove data, and they strictly enforce the LIFO (Last In, First Out) order.

PUSH is the insertion operation. It adds a new element at the TOP of the stack. You can keep pushing elements onto a stack until it becomes full. A stack is considered full when no more elements can be added to it. If you try to push an element onto a full stack, the program raises an exception called an overflow.

POP is the deletion operation. It removes the topmost element — the one currently at the TOP of the stack. You can keep popping elements from a stack until it becomes empty. If you try to pop an element from an empty stack, the program raises an exception called an underflow.

The textbook illustrates these operations using a pile of numbered glasses. The same LIFO principle applies: you can only add a glass to the top of the pile, and you can only remove a glass from the top. The sequence of operations in Figure 3.2 (as described in the text) is:

  • (i) Start with an empty stack.
  • (ii) Push 1 — glass 1 is placed on the stack. Top points to 1.
  • (iii) Push 2 — glass 2 is placed on top of glass 1. Top now points to 2.
  • (iv) Pop — the topmost element (glass 2) is removed. Top now points back to glass 1.
  • (v) Push 3 — glass 3 is placed on top of glass 1. Top points to 3.
  • (vi) Push 4 — glass 4 is placed on top of glass 3. Top points to 4.
  • (vii) Pop — glass 4 is removed. Top points back to glass 3.
  • (viii) Pop — glass 3 is removed. Top points back to glass 1.
  • (ix) Pop — glass 1 is removed. The stack becomes empty. …
Figure 3.2PUSH and POP operations on the stack of glasses
Fig. 3.2 — PUSH and POP operations on the stack of glasses

Drawn by us to help you understand the concept clearly, and verified to make sure it's accurate. For exams, practice from your NCERT textbook's own diagram.

This traces ten steps of PUSH and POP operations on a stack of glasses, with a Top -> arrow always pointing at whichever glass is currently on top.

Starting from an empty stack (i), each Push adds a new glass on top: Push 1 (ii) puts glass 1 in; Push 2 (iii) adds glass 2 above it, so Top now points at 2. Each Pop removes whatever is currently on top: Pop in (iv) removes glass 2 (since it was on top), leaving just glass 1, with Top moving back down to point at 1.

The sequence continues the same way — Push 3 (v), Push 4 (vi) build the stack back up to three glasses, then three Pops (vii)-(ix) remove them one at a time in the exact reverse of the order they were added: 4 first, then 3, then 1 — until the stack is empty again (x). …