Stack Operations Using Linked List

  1. Creation:

    • Define a Node class with data and next attributes.

    • Define a Stack class with a top attribute initialized to None.

  2. Push (insert an element to the top of the stack):

    • Create a new node with the given data.

    • Set the new node’s next attribute to the current top node.

    • Update the top attribute to the new node.

  3. Pop (remove an element from the top of the stack):

    • Check if the stack is empty.

    • Store the data from the top node.

    • Update the top attribute to the next node.

    • Return the stored data.

  4. IsEmpty (check if the stack is empty):

    • Return True if the top attribute is None, otherwise return False.

Dive into the world of data structures by implementing stack operations using linked lists in C. This guide walks you through the essential stack operations such as push, pop, peek, and checking if the stack is empty,

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

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

struct Node* top = NULL;

void push();
void pop();
void display();

int main() {
    int choose;
    while (1) {
        printf("\nEnter Operation\n");
        printf("1 for push operation\n");
        printf("2 for pop operation\n");
        printf("3 for display operation\n");
        printf("4 for exit operation\n");
        scanf("%d", &choose);
        
        if (choose == 4) {
            printf("You are exiting...\n");
            break;
        } 
        else if (choose == 1) {
            push();
        } 
        else if (choose == 2) {
            pop();
        } 
        else if (choose == 3) {
            display();
        } 
        else {
            printf("Error, Enter a valid operation\n");
        }
    }
    return 0;
}

void push() {
    int x;
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    if (newNode == NULL) {
        printf("Stack Overflow (Full)\n");
    } else {
        printf("Enter number to push: ");
        scanf("%d", &x);
        newNode->data = x;
        newNode->next = top;
        top = newNode;
    }
}

void pop() {
    if (top == NULL) {
        printf("Stack Underflow (Empty)\n");
    } else {
        struct Node* temp = top;
        printf("%d data is popped\n", top->data);
        top = top->next;
        free(temp);
    }
}

void display() {
    if (top == NULL) {
        printf("Stack is Empty\n");
    } else {
        struct Node* temp = top;
        printf("The elements in the stack are:\n");
        while (temp != NULL) {
            printf("%d\n", temp->data);
            temp = temp->next;
        }
    }
}

				
			

LEAVE A REPLY

Please enter your comment!
Please enter your name here