- 2068 Magh · 6+2 marks
Linked stack overcoming array demerits
Short answer
A linked stack dynamically allocates nodes on push and frees on pop, so there is no fixed-size overflow. Push inserts at top; pop removes top node. Both O(1), overcoming array stack’s fixed capacity and overflow issues.
Devise an algorithm that overcomes the demerits of array implementation of stack. Also verify your algorithm with necessary illustrations.
Demerits of array stack: fixed size (overflow even when memory is free, or wasted space when mostly empty), size must be known in advance, and it cannot grow at run time. A linked stack removes these: nodes are allocated on demand, so the stack grows and shrinks dynamically.
Algorithm (top = head of a singly linked list)
struct node { int info; struct node *next; };
struct node *top = NULL;
PUSH(x)
- Create node
pwith malloc; if NULL, overflow (heap full), stop. p->info = x; p->next = top; top = p.
POP()
- If
top == NULL, underflow, stop. p = top; x = p->info; top = top->next; free(p); returnx.
PEEK(): if top != NULL return top->info.
void push(int x) {
struct node *p = (struct node *)malloc(sizeof(struct node));
if (!p) { printf("Overflow\n"); return; }
p->info = x; p->next = top; top = p;
}
int pop(void) {
if (!top) { printf("Underflow\n"); return -1; }
struct node *p = top; int x = p->info;
top = top->next; free(p);
return x;
}
Verification
| Operation | Stack (top first) | Returned |
|---|---|---|
| push(5) | 5 | - |
| push(8) | 8, 5 | - |
| push(2) | 2, 8, 5 | - |
| pop() | 8, 5 | 2 |
| pop() | 5 | 8 |
| pop() | empty | 5 |
| pop() | underflow | - |
push(2): top -> [2]->[8]->[5]->NULL
pop(): top -> [8]->[5]->NULL ([2] freed)
Elements leave in last-in first-out order, and push/pop are O(1) with no size limit except available memory.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Stack and queue using linked list · Data Structure and Algorithm, chapter 4 · asked 2×
- Linked list considerations; array list in C · Data Structure and Algorithm, chapter 3
- Static vs dynamic implementation of stack · Data Structure and Algorithm, chapter 2
- Push and pop on stack as linked list · Data Structure and Algorithm, chapter 4
- Array implementation of list in C · Data Structure and Algorithm, chapter 3
- Dynamic implementation of queue · Data Structure and Algorithm, chapter 4
- Forward vs reverse engineering merits and demerits · Object Oriented Analysis and Design, chapter 4 · asked 3×