stack using linked list

PHOTO EMBED

Fri Jun 24 2022 12:49:54 GMT+0000 (Coordinated Universal Time)

Saved by @KanishqJ8

#include <stdio.h>
#include <stdlib.h>
struct Node{
    int data;
    struct Node* next;
};

struct Node*top=NULL;
void linkedListTraversal(struct Node*ptr){
    while(ptr!=NULL){
        printf("%d\n",ptr->data);
        ptr=ptr->next;
    }
}

int isEmpty(struct Node*top){
    if(top==NULL){
        return 1;
    }
    return 0;
}

int isFull(struct Node*top){
    struct Node*p = (struct Node*)malloc(sizeof(struct Node));
    if(p==NULL){
        return 1;
    }
    return 0;
}
struct Node* push(struct Node*top, int x){
    if(isFull(top)){
        printf("stack overflow\n");
    }
    struct Node*n=(struct Node* )malloc(sizeof(struct Node));
    n->data=x;
    n->next=top;
    top=n;
    return top;
}

int pop(struct Node*tp){
    if(isEmpty(top)){
        printf("stack underflow\n");
    }
    struct Node*n=tp;
    top=tp->next;
    int x=n->data;
    free(n);
    return x;
}

int main(){
    // struct Node*top = NULL; //we have to make this a global variable
    top = push(top,78);
    top = push(top,8);
    top = push(top,98);
    top = push(top,18);
    top = push(top,58);
    linkedListTraversal(top);
    printf("popped element is %d\n",pop(top));
    
    linkedListTraversal(top);
    return 0;
}
content_copyCOPY