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

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): insertxat the top.pop(): remove and return the top item.peek()ortop(): 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.
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 |
| none | 0 |
|
2 |
| none | 1 |
|
3 |
| none | 2 |
|
4 |
|
| 1 |
|
5 |
| none | 2 |
|
6 |
|
| 2 |
|
7 |
| none | 3 |
|
8 |
| none | 4 |
|
9 |
| overflow, rejected | 4 |
|
10 |
|
| 3 |
|
11 |
|
| 2 |
|
12 |
|
| 1 |
|
13 |
|
| 0 |
|
14 |
|
| -1 |
|
15 |
| 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.

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 |
|
|
A linked stack is neither infinite nor universally faster. Practise both representations until you can explain the storage trade-off without relying on syntax.

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. Testtop == capacity - 1before changingtop.Moving top before reading a pop: decrementing first returns the next item down. Save
S[top]beforetop = top - 1.Treating peek as pop: peek returns the value but must leave
topand 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 hastop = capacity - 1.Push changes
topbefore 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.
Keep learning
Stack Data Structure: Operations, Applications and Worked Examples
Build a stack from its LIFO rule, trace array and linked-list operations, evaluate a postfix expression, and practise recursion, applications, and common traps.
Data Structures: Types, Operations, Complexity, and Worked Examples
Learn how representations and operation costs shape data-structure choices. Follow one array and linked-list edit sequence, then apply the reasoning to stacks, queues, trees, and hashing.
UP LT Grade Computer Science: C, OOP and Data Structures with a Solved Trace
Learn a repeatable state-tracing method through one C program, compare stack, queue and linked-list operations, and classify OOP relationships by ownership.
Stack Basics and Operations MCQs: 12 Solved Questions with Step-by-Step Explanations
Test stack fundamentals through 12 exam MCQs on LIFO, TOP, array bounds, queue transfers and permutations. Complete traces make every state and answer checkable.





