Stack Linked List Implementation in C

Intermediate
6 min read
Updated: Nov 2026
1 example

Stack Backed by a Linked List

A linked stack uses the list head as the top. push allocates a node and links it in front; pop unlinks the head and frees it. There is no capacity limit (until memory runs out) and both operations are O(1). Each element costs an extra pointer.

Remember
push: n->next = top; top = n;
pop : n = top; top = n->next; free(n);

Cheat Sheet

Keep these facts handy while you work with Stack Linked List Implementation in C in C.

TopicDetail
TopHead of the list
PushAllocate + link in front
PopUnlink + free
Emptytop == NULL

C Examples

Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Stack Overflow and Underflow.

Example 1 — A linked stack

Push 1, 2, 3 and pop them all.

C
#include <stdio.h>
#include <stdlib.h>

struct Node { int data; struct Node *next; };

static void push(struct Node **top, int v) {
    struct Node *n = malloc(sizeof *n);
    if (!n) exit(1);
    n->data = v;
    n->next = *top;
    *top = n;
}
static int pop(struct Node **top) {
    struct Node *n = *top;
    int v = n->data;
    *top = n->next;
    free(n);
    return v;
}

int main(void) {
    struct Node *top = NULL;
    push(&top, 1); push(&top, 2); push(&top, 3);

    while (top) printf("pop: %d\n", pop(&top));
    printf("empty: %d\n", top == NULL);
    return 0;
}

How It Works

  1. Each push adds a node at the head, so the newest item is first.
  2. pop frees the removed node after saving its value.
  3. The loop stops when top is NULL.

Edge Cases & Pitfalls

Check these before relying on Stack Linked List Implementation in C in real programs.

empty

Popping when empty

pop dereferences top. Check top != NULL first.

leak

Leaving items on exit

Pop or free the remaining nodes.

Key Takeaways

  • Head is the top.
  • No fixed capacity.
  • Free popped nodes.

One line: A linked stack uses the list head as the top.

Frequently Asked Questions

It grows and shrinks one node at a time with no capacity limit and no reallocation.
Both are O(1), but arrays are usually faster in practice because of better cache locality and no allocation per push.
Continue with "C Stack Overflow and Underflow" next. Detect and handle full and empty stacks. The C Stacks hub lists every topic in order.

Next: Stack Overflow and Underflow

Detect and handle full and empty stacks.

Continue →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

11 people found this page helpful