Course contentsShow
← C
Lesson 1008 of 1,21914. Data Structures in CFree lesson

Linked list-based stack implementation

Linked list-based stack implementation

What you'll learn: How to use a linked list to create a stack that grows and shrinks dynamically without a fixed size limit.

While an array-based stack is like a Pringles can with a set height, a linked list-based stack is more like a magic vertical train. You can add as many cars as you want to the front, and the "engine" always points to the most recently added car. In programming terms, the "Top" of our stack is simply the head of a linked list.

The logic of LIFO with nodes

In a linked list stack, every element is a node containing two things: the data and a pointer to the next node.

  1. Pushing: To push a new value, we create a new node. We point this new node's next pointer to the current top. Then, we update top to point to our new node. The new node is now the king of the hill.
  2. Popping: To pop, we look at where top is pointing. We save that data, move the top pointer to the next node in line, and then free the memory of the old top node.

Because we allocate memory for each node as we go, we never have to worry about the stack being "full" (unless your computer runs out of RAM entirely).

Building the stack in C

Here is how we represent the stack structure and the core "Push" operation. Notice how we always insert at the beginning of the list to keep the operation fast.

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

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

// The 'top' is just a pointer to the first node
struct Node* top = NULL;

void push(int value) {
    // 1. Allocate memory for a new node
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    
    // 2. Assign data and link it to the current top
    newNode->data = value;
    newNode->next = top;
    
    // 3. Move the top to point to the new node
    top = newNode;
    printf("Pushed %d to the stack\n", value);
}

int pop() {
    if (top == NULL) {
        printf("Stack Underflow\n");
        return -1;
    }
    // 1. Temporary pointer to hold the node to be removed
    struct Node* temp = top;
    int poppedValue = temp->data;
    
    // 2. Move top to the next node
    top = top->next;
    
    // 3. Free the memory of the old node
    free(temp);
    return poppedValue;
}

Why use a linked list?

Using a linked list for a stack is incredibly efficient for memory management. If your program only needs three items, the stack only uses three nodes. If it needs three thousand, it grows to fit. Unlike arrays, you don't have to guess the maximum size in advance or "resize" the array, which can be a slow process. As long as you remember to free() your nodes when you pop them, your stack will be lean and fast.

Key takeaway

A linked list stack uses a head pointer as the top, allowing the stack to grow and shrink dynamically by adding or removing nodes from the front of the list.