Skip to main content

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)

  1. Create node p with malloc; if NULL, overflow (heap full), stop.
  2. p->info = x; p->next = top; top = p.

POP()

  1. If top == NULL, underflow, stop.
  2. p = top; x = p->info; top = top->next; free(p); return x.

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

OperationStack (top first)Returned
push(5)5-
push(8)8, 5-
push(2)2, 8, 5-
pop()8, 52
pop()58
pop()empty5
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)

All Data Structure and Algorithm chapter 4 questions →