Previous method: https://marxtudor.com/stack-using-linked-list-c-program/
In this method pointer variable top is not declared in the global section its declared in the main() function. So we need to return the value of top each time the value of top is changed when the node is inserted or deleted so that the value of top gets updated.
In this method pointer variable top is not declared in the global section its declared in the main() function. So we need to return the value of top each time the value of top is changed when the node is inserted or deleted so that the value of top gets updated.
#include#include struct node{ int info; struct node *link; }; void display(struct node *top); struct node *push(struct node *top, int num); struct node *pop(struct node *top); main() { struct node *top=NULL; int choice, num; while(1) { printf("n1 Pushn"); printf("2 Popn"); printf("3 Displayn"); printf("4 Exitnn"); scanf("%d",&choice); switch(choice) { case 1: printf("Enter the number to be insertedn"); scanf("%d",&num); top = push(top, num); break; case 2: top = pop(top); break; case 3: display(top); break; case 4: exit(1); default: printf("Invalid Input"); } } } struct node *push(struct node *top, int num) { struct node *temp; temp=(struct node *)malloc(sizeof(struct node)); temp->info=num; temp->link = top; top = temp; return top; } struct node *pop(struct node *top) { struct node *temp; int num; if (top==NULL) { printf("underflown"); return; } temp=top; num = top->info; top = top->link; free(temp); printf("Deleted number is %d",num); return top; } void display(struct node *top) { struct node *p; if(top==NULL) { printf("nList is emptyn"); return; } p=top; printf("n Stack is: n"); while(p != NULL) { printf("%dn", p->info); p=p->link; } }