Stack using linked list

1) Stack using Linked List

Aim

To implement stack operations (Push, Pop, Display) using singly linked list in C.

Objective

  • To understand dynamic memory allocation with linked lists.

  • To implement LIFO (Last In, First Out) principle.

Algorithm

Push:

  1. Create a new node.

  2. Insert new node at beginning.

  3. Update top pointer.

Pop:

  1. If stack empty, print underflow.

  2. Else remove first node.

  3. Update top pointer.

Display:

  1. Traverse from top to NULL.

  2. Print each node’s data.

Flowchart

Flowchart - C Program to implement a Stack

C Code (Stack using Linked List)

#include <stdio.h>

#include <stdlib.h>

struct Node {

    int data;

    struct Node* next;

};

int main() {

    struct Node* top = NULL;

    struct Node* temp;

    int choice, item;

    while (1) {

        printf("\n--- Stack Menu (Linked List) ---\n");

        printf("1. Push\n2. Pop\n3. Display\n4. Exit\n");

        printf("Enter choice: ");

        scanf("%d", &choice);

        if (choice == 1) {  // Push

            printf("Enter item to push: ");

            scanf("%d", &item);

            struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));

            newNode->data = item;

            newNode->next = top;

            top = newNode;

        }

        else if (choice == 2) {  // Pop

            if (top == NULL)

                printf("Stack Underflow!\n");

            else {

                temp = top;

                printf("Popped: %d\n", temp->data);

                top = top->next;

                free(temp);

            }

        }

        else if (choice == 3) {  // Display

            if (top == NULL)

                printf("Stack is Empty!\n");

            else {

                printf("Stack elements: ");

                temp = top;

                while (temp != NULL) {

                    printf("%d ", temp->data);

                    temp = temp->next;

                }

                printf("\n");

            }

        }

        else if (choice == 4) {

            printf("Exiting...\n");

            break;

        }

        else {

            printf("Invalid choice!\n");

        }

    }

    return 0;

}

 

Comments

Popular posts from this blog

Stack using array

Bubble Sort

Singly linked list implementation