Skip to content
Azhimathi Mayam logoDSA Study HubPCCST303 · KTU · S3
Module 2 · syllabusLesson live

Stacks and queues using linked lists

A stack and a queue that never overflow (until memory runs out) — built from linked nodes.

Syllabus says: “Stacks and Queues using Linked List”

On this page · 10 sections
ormakkurippu ✎
Never-forget card

Linked STACK: everything happens at the HEAD. Linked QUEUE: join at the REAR, leave from the FRONT.

Picture it

Stack = a pile of chapatis: new ones on top, you eat from the top. Queue = the ration-shop line: join at the back, get served at the front.

Write this in the exam

A linked stack inserts and deletes at the front of a list (top = head); a linked queue keeps front and rear pointers, inserting at the rear and deleting at the front, all in O(1).

What you will be able to do

  • Implement push and pop using a linked list.
  • Implement insert and delete for a linked queue with front and rear pointers.

Linked queue

front102030NULL
front → 10 … rear → 30. Insert after 30, delete 10.
algorithm
Algorithm Insert(x)          // enqueue at rear
1. new ← getNode(x)           // new→link = NULL
2. if front = NULL then front ← rear ← new
3. else rear→link ← new;  rear ← new

Algorithm Delete()           // dequeue at front
1. if front = NULL then print "Queue underflow"; return
2. t ← front;  x ← t→data
3. front ← front→link
4. if front = NULL then rear ← NULL      // queue became empty
5. free(t);  return x

Linked stack

top302010NULL
After push 10, push 20, push 30 — top points to the latest element.
algorithm
Algorithm Push(x)
1. new ← getNode(x)     // if malloc fails → "Stack overflow (no memory)"
2. new→link ← top
3. top ← new

Algorithm Pop()
1. if top = NULL then print "Stack underflow"; return
2. t ← top;  x ← t→data
3. top ← top→link
4. free(t);  return x

Now watch it run

Every frame comes from really running the algorithm on your input — change it and break it! Tap ▶ Play, or step one frame at a time with ◀ ▶.

Loading visualizer…

Also try: Linked queue

C implementation

linked_stack_queue.ctested ✓ 320/320 cases
C
/* Stack and queue using linked lists — KTU PCCST303, Module 2
 * Linked stack: push and pop at the front (top). Linked queue: insert at rear, delete at front.
 * No overflow check is needed except when malloc fails.
 * First line: S (stack) or Q (queue). Then commands: PUSH x | POP | PEEK  or  ENQ x | DEQ
 * After every command: optional result line, then "LIST: ..." (top→bottom or front→rear). */
#include <stdio.h>
#include <stdlib.h>

struct node {
    int data;
    struct node *next;
};
struct node *top = NULL;                      /* stack */
struct node *front = NULL, *rear = NULL;      /* queue */

struct node *getNode(int x) {
    struct node *n = malloc(sizeof *n);
    if (n == NULL) { printf("OUT OF MEMORY\n"); exit(1); }
    n->data = x;
    n->next = NULL;
    return n;
}

void push(int x) { struct node *n = getNode(x); n->next = top; top = n; }

void pop(void) {
    struct node *t;
    if (top == NULL) { printf("UNDERFLOW\n"); return; }
    t = top;
    top = top->next;
    printf("popped %d\n", t->data);
    free(t);
}

void peek(void) {
    if (top == NULL) { printf("UNDERFLOW\n"); return; }
    printf("top is %d\n", top->data);
}

void enqueue(int x) {
    struct node *n = getNode(x);
    if (rear == NULL) front = rear = n;       /* first node is both front and rear */
    else { rear->next = n; rear = n; }
}

void dequeue(void) {
    struct node *t;
    if (front == NULL) { printf("UNDERFLOW\n"); return; }
    t = front;
    front = front->next;
    if (front == NULL) rear = NULL;           /* queue became empty */
    printf("dequeued %d\n", t->data);
    free(t);
}

void display(struct node *p) {
    printf("LIST:");
    for (; p != NULL; p = p->next) printf(" %d", p->data);
    printf("\n");
}

int main(void) {
    char kind[4], cmd[8];
    int x;
    if (scanf("%3s", kind) != 1) return 1;
    while (scanf("%7s", cmd) == 1) {
        if (cmd[0] == 'P' && cmd[1] == 'U' && scanf("%d", &x) == 1) push(x);
        else if (cmd[0] == 'P' && cmd[1] == 'O') pop();
        else if (cmd[0] == 'P' && cmd[1] == 'E') peek();
        else if (cmd[0] == 'E' && scanf("%d", &x) == 1) enqueue(x);
        else if (cmd[0] == 'D') dequeue();
        else { printf("BAD COMMAND\n"); break; }
        display(kind[0] == 'S' ? top : front);
    }
    while (top != NULL) { struct node *t = top; top = top->next; free(t); }
    while (front != NULL) { struct node *t = front; front = front->next; free(t); }
    return 0;
}
Sample run · linked queue · real output from gcc

Input (stdin)

Q
ENQ 10
ENQ 20
DEQ
ENQ 30
DEQ
DEQ
DEQ

Output (stdout)

LIST: 10
LIST: 10 20
dequeued 10
LIST: 20
LIST: 20 30
dequeued 20
LIST: 30
dequeued 30
LIST:
UNDERFLOW
LIST:

Open in the Code Lab →

Complexity

Every operation is O(1). Space is O(n) plus one pointer per node, with no wasted slots and no ‘queue full’ problem like the array version.

Quick check — can you get them all?

Question 1

Q1.In a linked stack, push corresponds to…

Question 2

Q2.Linked queue: after deleting the only node, what else must change?

Question 3

Q3.When does a linked stack overflow?

Practice

Every visualizer has a Practice mode: predict the next state before the animation reveals it. You can also work through the topic's question set on the practice page.

Exam-ready summary

  • Stack: push = insert at head, pop = delete head.
  • Queue: insert at rear, delete at front; reset rear when the queue becomes empty.
  • Overflow only when malloc fails. All O(1).

References

  • Horowitz, Sahni & Anderson-Freed, Fundamentals of Data Structures in C, 2/e — §4.3 (Dynamically linked stacks and queues)

Explanations on this page are original. Textbook references point to where the standard treatment can be read; no text is reproduced from them.

Prefer revising from notes? Module-wise notes and question papers on Azhimathi Mayam (opens in a new tab)