Skip to main content

Stack using Linked list

 




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

struct node{
    int data;
    struct node *link;
};
struct node* top =NULL;
void display(struct node *ptr){
    while(ptr!=NULL){
        printf(" %d\n",ptr->data);
        ptr = ptr->link;
    }
}
void push(){
    struct node *temp;
    temp = malloc(sizeof(struct node));
    printf("Enter the element: ");
    scanf("%d",&temp->data);
    temp->link = top;
    top = temp;
}
void pop(){
    struct node *t;
    if(top == NULL){
        printf("Stack is empty\n");
    }
    else{
        t = top;
        printf("Popped element: %d\n",top->data);
        top = top->link;
        t->link = NULL;
        free(t);
    }
}
int main()
{

    // top = push(top,1);
    // top = push(top,2);
    // top = push(top,3);
    // top = push(top,4);
    // top = push(top,5);
    // pop(top);
    // display(top);
 
    while(1){
        int a;
        printf("1. Push\n");
        printf("2. PoP\n");
        printf("3. Display\n");
        printf("4. Exit\n");
        printf("Enter you choice: ");
        scanf("%d",&a);
        switch (a)
        {
        case 1:
            push();
            break;
        case 2:
            pop();
            break;
        case 3:
            display(top);
            break;
        case 4:
            exit(0);
            break;
       
        default:
            printf("Wrong Input!");
            break;
        }
    }

    return 0;
}


Comments