Topic 4
Stack
LIFO โ Last In, First Out
A stack is like a pile of plates. You can only add/remove from the top.
4 Operations:
โข push(value) โ add to top
โข pop() โ remove top
โข peek() โ view top without removing
โข display() โ print all (top to bottom)
Push order: 10, 20, 30
30โ top
20
10
After pop() โ returns 30
20โ top
10
๐
Array:
top = -1. Push: arr[++top]. Pop: arr[top--]๐
LL: Push = insert at head. Pop = delete head. No overflow!
๐
isFull():
top == maxSize - 1 (array only!). LL has no isFull.๐
Display: Array prints
top โ 0. LL traverses current โ NULL.Array Stack vs Linked List Stack
| Aspect | Array | Linked List |
|---|---|---|
| Size | Fixed (needs maxSize) | Dynamic (grows as needed) |
| Overflow | top == maxSize-1 | No overflow possible |
| Top variable | int top = -1 | Node* top = NULL |
| Push | arr[++top] = value | newNode->next = top |
| Pop | return arr[top--] | Save data, move top, delete |
| Memory | Contiguous block | Scattered nodes |
| Destructor | delete[] arr | Loop pop() until empty |