DATA STRUCTURES PROGRAM • STACKS & EXPRESSIONS

Implement a Stack Using a Linked List

Learn how to implement a stack using a linked list using a clear C program.

BeginnerStackLIFOpush/pop

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
Popped = 30
Top = 20

COMPLETE C PROGRAM

Complete C implementation

dsa-stack-linked-list.c
Open in compiler
#include <stdio.h>
#include <stdlib.h>

struct Node { int data; struct Node *next; };
void push(struct Node **top, int value)
{
    struct Node *node = malloc(sizeof *node);
    if (node == NULL) exit(EXIT_FAILURE);
    node->data = value; node->next = *top; *top = node;
}
int pop(struct Node **top)
{
    if (*top == NULL) { puts("Stack underflow."); exit(EXIT_FAILURE); }
    struct Node *removed = *top; int value = removed->data;
    *top = removed->next; free(removed); return value;
}

int main(void)
{
    struct Node *top = NULL;
    push(&top, 10); push(&top, 20); push(&top, 30);
    printf("Popped = %d\n", pop(&top));
    printf("Top = %d\n", top->data);
    while (top != NULL) pop(&top);
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Popped = 30
Top = 20
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Treat the list head as the stack top for constant-time insertion and deletion.
  3. Display the computed result.

Treat the list head as the stack top for constant-time insertion and deletion.

EFFICIENCY

Time and space complexity

Time complexity

O(1) per operation

Auxiliary space

O(n)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.