- 2070 Bhadra · 1+4 marks
Static vs dynamic implementation of stack
Short answer
A stack is a linear LIFO structure. Static implementation uses a fixed-size array with top index; overflow at MAX-1. Dynamic implementation uses a linked list with top pointing to head node; memory allocates/frees as needed, no fixed overflow but extra pointer per node.
Define Stack. How does static implementation and dynamic implementation of stack differ? Explain.
A stack is a linear data structure in which insertion (push) and deletion (pop) take place only at one end, called the top. The last element inserted is the first one removed, so it follows LIFO (Last In First Out).
Static (array) and dynamic (linked list) implementation
In static implementation the stack is stored in an array of fixed size declared at compile time. In dynamic implementation the stack is a linked list whose nodes are created with malloc when pushed and freed when popped; the pointer top points to the first node.
| Static (array) | Dynamic (linked list) |
|---|---|
| Fixed size, set at compile time | Grows and shrinks at run time |
Overflow when top == MAX-1 | Overflow only when heap memory is exhausted |
| Memory may be wasted if stack is small | Memory used equals number of items (plus pointer per node) |
| No extra pointer field | Each node needs an extra pointer |
| Contiguous memory | Nodes scattered in memory |
| Simple and fast | Slightly slower (allocation, pointer handling) |
top is an integer index | top is a pointer to the top node |
Static code
int s[MAX], top = -1;
void push(int x) { if (top == MAX-1) printf("Overflow"); else s[++top] = x; }
int pop() { return (top == -1) ? -1 : s[top--]; }
Dynamic code
struct node { int info; struct node *next; };
struct node *top = NULL;
void push(int x) {
struct node *p = (struct node *)malloc(sizeof(struct node));
p->info = x; p->next = top; top = p; /* insert at beginning */
}
int pop() {
if (top == NULL) { printf("Underflow"); return -1; }
struct node *p = top; int x = p->info;
top = top->next; free(p); /* delete first node */
return x;
}
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Static vs dynamic implementation of list · Data Structure and Algorithm, chapter 3 · asked 2×
- Static vs dynamic list; getnode and freenode · Data Structure and Algorithm, chapter 3
- Why choose static or dynamic list · Data Structure and Algorithm, chapter 3
- Array list; static or dynamic choice · Data Structure and Algorithm, chapter 3
- Static and dynamic data structures; array list · Data Structure and Algorithm, chapter 3
- Dynamic implementation of queue · Data Structure and Algorithm, chapter 4
- Static vs dynamic mathematical model · Simulation and Modeling, chapter 2 · asked 3×
- Static and dynamic hazards and their elimination · Digital Logic, chapter 3 · asked 2×
- Static versus dynamic binding trade-offs · Object Oriented Programming, chapter 7
- Static and dynamic errors in DAC · Instrumentation II, chapter 4