Implement a stack using linked lists in C

 #include <stdio.h>

#include <stdlib.h>


// Node structure for stack

struct Node {

    int data;

    struct Node* next;

};


// Top pointer for stack

struct Node* top = NULL;


// Push operation

void push(int value) {

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

    if (!newNode) {

        printf("Heap Overflow\n");

        return;

    }

    newNode->data = value;

    newNode->next = top;

    top = newNode;

    printf("%d pushed to stack.\n", value);

}


// Pop operation

int pop() {

    if (top == NULL) {

        printf("Stack Underflow! Cannot pop.\n");

        return -1;

    }

    int popped = top->data;

    struct Node* temp = top;

    top = top->next;

    free(temp);

    return popped;

}


// Peek operation

int peek() {

    if (top == NULL) {

        printf("Stack is empty.\n");

        return -1;

    }

    return top->data;

}


// Check if stack is empty

int isEmpty() {

    return top == NULL;

}


// Display the stack

void display() {

    if (isEmpty()) {

        printf("Stack is empty.\n");

        return;

    }

    struct Node* temp = top;

    printf("Stack elements (top to bottom): ");

    while (temp != NULL) {

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

        temp = temp->next;

    }

    printf("\n");

}


// Main function to test stack

int main() {

    int choice, value;


    while (1) {

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

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

        printf("Enter your choice: ");

        scanf("%d", &choice);


        switch (choice) {

        case 1:

            printf("Enter value to push: ");

            scanf("%d", &value);

            push(value);

            break;

        case 2:

            value = pop();

            if (value != -1)

                printf("Popped element: %d\n", value);

            break;

        case 3:

            value = peek();

            if (value != -1)

                printf("Top element: %d\n", value);

            break;

        case 4:

            display();

            break;

        case 5:

            printf("Exiting program.\n");

            return 0;

        default:

            printf("Invalid choice! Please try again.\n");

        }

    }

}

Output:


Comments