Skip to content
Laviyx Learn

Try

DS Lab · Experiment 5

Stack using a linked list (pointers)

CStacks and queuesJNTUH R22 · CS306PC

Aim

To write a menu-driven C program that implements a stack using a singly linked list (pointers), with the operations push, pop, peek and display, and reports underflow.

Algorithm

  1. Define a node with data and next. Keep a pointer top to the top node; top = NULL means the stack is empty.
  2. Push x: allocate a new node with malloc, store x, set new->next = top, then top = new.
  3. Pop: if top is NULL, report underflow. Otherwise save top, move top to top->next, print the saved data and free the saved node.
  4. Peek: if the stack is empty, report it. Otherwise show top->data.
  5. Display: follow next pointers from top and print each node.
  6. Repeat the menu until the user chooses Exit, then pop and free every remaining node.

Program

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

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

struct node *top = NULL;    /* NULL means the stack is empty */

void push(int value) {
    struct node *newnode = malloc(sizeof(struct node));
    if (newnode == NULL) {
        printf("Stack overflow (no memory left)\n");
        return;
    }
    newnode->data = value;
    newnode->next = top;    /* new node sits on top of the old top */
    top = newnode;
    printf("Pushed %d\n", value);
}

void pop(void) {
    if (top == NULL) {
        printf("Stack underflow, nothing to pop\n");
        return;
    }
    struct node *temp = top;
    top = top->next;
    printf("Popped %d\n", temp->data);
    free(temp);
}

void peek(void) {
    if (top == NULL) {
        printf("Stack is empty\n");
    } else {
        printf("Top element is %d\n", top->data);
    }
}

void display(void) {
    if (top == NULL) {
        printf("Stack is empty\n");
        return;
    }
    printf("Stack (top to bottom): ");
    for (struct node *temp = top; temp != NULL; temp = temp->next) {
        printf("%d ", temp->data);
    }
    printf("\n");
}

void free_stack(void) {
    while (top != NULL) {
        struct node *temp = top;
        top = top->next;
        free(temp);
    }
}

int main(void) {
    int choice, value;

    printf("STACK USING LINKED LIST\n");
    printf("1. Push\n2. Pop\n3. Peek\n4. Display\n5. Exit\n");

    do {
        printf("\nEnter your choice: ");
        if (scanf("%d", &choice) != 1) {
            printf("Invalid input\n");
            break;
        }
        switch (choice) {
        case 1:
            printf("Enter value to push: ");
            if (scanf("%d", &value) == 1) {
                push(value);
            }
            break;
        case 2:
            pop();
            break;
        case 3:
            peek();
            break;
        case 4:
            display();
            break;
        case 5:
            break;
        default:
            printf("Invalid choice\n");
        }
    } while (choice != 5);

    free_stack();
    printf("All nodes freed. Exiting.\n");
    return 0;
}

Output

Output
STACK USING LINKED LIST
1. Push
2. Pop
3. Peek
4. Display
5. Exit

Enter your choice: 2
Stack underflow, nothing to pop

Enter your choice: 1
Enter value to push: 10
Pushed 10

Enter your choice: 1
Enter value to push: 20
Pushed 20

Enter your choice: 1
Enter value to push: 30
Pushed 30

Enter your choice: 4
Stack (top to bottom): 30 20 10 

Enter your choice: 3
Top element is 30

Enter your choice: 2
Popped 30

Enter your choice: 2
Popped 20

Enter your choice: 4
Stack (top to bottom): 10 

Enter your choice: 5
All nodes freed. Exiting.

Recorded by compiling and running this exact program. Typed input appears after each prompt.

How it works

The top of the stack is the head of the linked list, so push is "insert at beginning" and pop is "delete from beginning". Both take O(1) time.

There is no fixed size, so the only way to get overflow is when malloc cannot find memory and returns NULL. The node still on the stack at Exit is freed by free_stack.

Common mistakes

  • Pushing at the end of the list instead of the beginning. Push and pop then need to walk the whole list, which makes them O(n) instead of O(1).

  • Freeing top and then reading top->next. Move top to the next node first, keeping the old node in a temporary pointer, and free that.

  • Not checking the result of malloc for NULL.

  • Forgetting to free the remaining nodes before the program ends.

Viva questions

Try to answer each one aloud before you open it.

  • Why implement a stack with a linked list instead of an array?

    A linked list stack grows and shrinks as needed, so there is no fixed size and no overflow until memory runs out. An array stack has a fixed size.

  • Which end of the linked list is used as the top, and why?

    The head. Inserting and deleting at the head takes O(1) time, while working at the tail of a singly linked list needs a walk through the whole list.

  • When does overflow happen in a linked list stack?

    Only when malloc fails because no memory is left, in which case it returns NULL.

  • What is the disadvantage compared with an array stack?

    Each element needs extra memory for the next pointer, and allocating a node with malloc for every push is slower than storing into an array.

Learn the concepts

All Data Structures Lab experiments →