Stack Operations in Data Structures: Push, Pop, Peek, a Worked Trace and Exam Traps

Learn how stack invariants control push, pop and peek. Follow a capacity-5 trace through normal operations, overflow and underflow, then practise a reliable method for output questions.

KnowledgeGate Team

Exam prep & CS education

Updated 6 Nov 20266 min read
Stack Operations in Data Structures: Push, Pop, Peek, a Worked Trace and Exam Traps

Remembering that a stack follows LIFO is easy. Output questions become difficult when you mix up the top index, the value returned by an operation, and the elements that remain in the stack. The earlier Stack Data Structure: Operations, Applications and Worked Examples connects stack operations to expressions, recursion and applications in a compact capacity-4 example. The guard-by-guard capacity-5 trace below carries its 12, 7, 25 seed onward through both overflow and underflow. For the wider subject path, use Coding & DSA Courses for Placements.

Stack basics: LIFO, the top element and the stack ADT

A stack is an abstract data type whose insertion and deletion happen at one accessible end, called top. Under last in, first out (LIFO), a pop returns the most recently pushed item. The ADT defines behaviour; arrays and linked lists implement it.

The core operations are:

  • push(x): insert x at the top.

  • pop(): remove and return the top item.

  • peek() or top(): return the top item without removing it.

  • isEmpty(): test whether an item can be removed.

  • isFull(): for a fixed-capacity array, test whether another item can be inserted.

An empty stack has no valid top. A queue removes the oldest item, while a stack removes the newest. Stacks and queues: operations, applications and the exam angle covers the wider LIFO-versus-FIFO comparison, circular queues and shared applications. Stack-only questions instead turn on state updates, fixed-capacity boundaries and representation rules.

Array stack operations: invariants behind push, pop and peek

Use an array S[0..4] with capacity 5 and an integer top. An empty stack has top = -1, size is top + 1, and a full stack has top = capacity - 1 = 4. The live elements occupy exactly S[0] through S[top]. Each guard must pass before the state changes.

Code
PUSH(x):
    if top == 4: signal overflow
    else:
        top = top + 1
        S[top] = x

POP():
    if top == -1: signal underflow
    else:
        x = S[top]
        top = top - 1
        return x

PEEK():
    if top == -1: signal empty stack
    else: return S[top]

For this fixed array, every listed operation takes O(1) time. Storage is Theta(capacity), conventionally Theta(n) when capacity scales with maximum size n. Dynamic-array push is amortised O(1), but a resize takes O(n).

Stack worked example: a capacity-5 trace through every boundary

Start with S = [_, _, _, _, _], top = -1 and size 0. Apply each guard before changing the state.

step

operation

returned or signalled

top after

contents bottom -> top

0

start

none

-1

[]

1

PUSH(12)

none

0

[12]

2

PUSH(7)

none

1

[12, 7]

3

PUSH(25)

none

2

[12, 7, 25]

4

POP()

25

1

[12, 7]

5

PUSH(18)

none

2

[12, 7, 18]

6

PEEK()

18

2

[12, 7, 18]

7

PUSH(4)

none

3

[12, 7, 18, 4]

8

PUSH(30)

none

4

[12, 7, 18, 4, 30]

9

PUSH(9)

overflow, rejected

4

[12, 7, 18, 4, 30]

10

POP()

30

3

[12, 7, 18, 4]

11

POP()

4

2

[12, 7, 18]

12

POP()

18

1

[12, 7]

13

POP()

7

0

[12]

14

POP()

12

-1

[]

15

POP()

underflow, rejected

-1

[]

The successful pop sequence is 25, 30, 4, 18, 7, 12. PEEK() returns 18 without changing the state. Six successful pushes reach the peak size 5, and six successful pops empty the stack. The overflow and underflow guards reject one operation each without changing top or any live slot.

A popped value may remain physically in an array cell, but it is stale. Only indices 0..top belong to the logical stack.

Seven snapshots of a capacity-5 array stack, from top = -1 through a full stack, a rejected overflow push and a rejected underflow pop.

Linked stack representation: same ADT, different storage rule

After step 5, [12, 7, 18] becomes top -> 18 -> 7 -> 12 -> NULL in a linked stack. Push links a new node to the old top. Pop saves the top value, advances the pointer and releases the removed node.

In either representation, POP() returns 18 and leaves [12, 7]. Storage changes, but LIFO behaviour does not; basic operations never use the bottom end.

Property

Fixed array stack

Linked stack

Layout

Contiguous reserved slots

One separately allocated node at a time

Capacity limit

Overflows when fixed capacity is full

Grows until allocation fails

Extra storage

Reserved array slots

One link per node

Push, pop, peek

O(1)

O(1) at the top end

A linked stack is neither infinite nor universally faster. Practise both representations until you can explain the storage trade-off without relying on syntax.

Array and linked views of the stack 12, 7, 18, where one pop returns 18 and leaves 12, 7 in both representations.

Stack applications: bracket matching needs only the top

Scan ([{}]) from left to right. Pushing each opener gives ['('], ['(', '['], then ['(', '[', '{']. Next, } pops {, ] pops [, and ) pops (. Every closer matches the current top, and the final empty stack proves the input is balanced.

For ([)], the scan fails when ) meets top [. A matching ( deeper in the stack cannot help because the latest unmatched opener must close first. The same rule supports function calls, undo history, depth-first traversal and postfix evaluation.

Stack operation traps: updates, boundaries and complexity

Pair each common trap with its correction:

  • Checking overflow too late: incrementing first can write beyond index 4. Test top == capacity - 1 before changing top.

  • Moving top before reading a pop: decrementing first returns the next item down. Save S[top] before top = top - 1.

  • Treating peek as pop: peek returns the value but must leave top and size unchanged.

Keep values, indices and size separate. After step 6, the top value is 18, the top index is 2, and size is top + 1 = 3. All three statements are correct, but they answer different questions.

A linked stack can fail when memory allocation fails. A dynamic-array push is not worst-case O(1) if it triggers a resize. Random access is also not a core stack operation, even when the underlying array could technically expose an index.

Stack exam questions: traces, code output and representation choices

Questions may ask for the final top and size, returned values, overflow or underflow, a code repair, a representation comparison, or a time bound. Use Stacks and Queues MCQs: 12 Solved (GATE) for practice. The KnowledgeGate question bank has over 80 live practice questions on stack basics and operations.

For a quick independent check, take capacity 4 and run PUSH(3), PUSH(8), POP(), PUSH(5), PUSH(2), PEEK() from empty. The pop returns 8. The final stack is [3, 5, 2], top = 2, size is 3, and peek returns 2 without changing anything.

On scratch paper, write top = -1 and make one row per operation. Update top only after the guard passes. Record returned values separately from the contents, and cross out a rejected operation without changing the state.

Stack operations in data structures: the short version and next step

  • The newest item leaves first.

  • An empty array stack has top = -1; a full fixed array has top = capacity - 1.

  • Push changes top before storing the new value.

  • Pop saves the value before reducing top.

  • Peek changes nothing.

Now reproduce the full pop sequence 25, 30, 4, 18, 7, 12 without looking at the table. For a structured route through the wider GATE CS syllabus, continue with GATE Guidance by Sanchit Sir.