- 2073 Bhadra · 5 marks
Push and pop on stack as linked list
Short answer
Push: allocate a new node, assign its next to the current top, and update top to this new node. Pop: store the top node’s info, advance top to the next node, free the old top. Both operations are O(1).
How do you perform a push and pop operation in stack as a linked list?
A stack as a linked list keeps its top at the head of a singly linked list, so push and pop both work at the front. Nodes are created with malloc, hence no fixed size limit.
struct node { int info; struct node *next; };
struct node *top = NULL;
PUSH(x)
- Create node
pusing malloc; if NULL, print "overflow" and stop. p->info = x.p->next = top(new node points to the old top).top = p.
POP()
- If
top == NULL, print "underflow" and stop. p = top.x = p->info.top = top->next.free(p); returnx.
Initial: push(30): pop():
top -> [20]->[10] top -> [30]->[20]->[10] top -> [20]->[10] (returns 30)
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;
}
Both operations take O(1) time.
✓ 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 stack overcoming array demerits · Data Structure and Algorithm, chapter 4
- Stack definition and basic operations · Data Structure and Algorithm, chapter 2
- Insert and delete kth node in doubly linked list · Data Structure and Algorithm, chapter 4 · asked 2×
- Delete last node of doubly linked list · Data Structure and Algorithm, chapter 4
- Doubly linked list: bank customer records · Data Structure and Algorithm, chapter 4
- PC and SP in CALL, RET, PUSH, POP · Microprocessor, chapter 2
- Compare CALL/RET with PUSH/POP · Microprocessor, chapter 2
- IRQ, ISR, IVT, PUSH, POP, latency · Embedded System, chapter 5
- Justify EMS expenditure; push-pull SCM · Information System, chapter 3