//Write a program to implement Stack using Linked List
#include<stdio.h>
#include<stdlib.h>
typedef struct node {
int data;
struct node *link;
} NODE;
NODE *start = NULL, *top = NULL;
void push(int item) {
NODE *ptr = (NODE *)malloc(sizeof(NODE));
if (ptr == NULL) {
printf("\nMemory allocation failed.\n");
exit(1);
}
ptr->data = item;
ptr->link = top;
top = ptr;
}
void pop() {
if (top == NULL) {
printf("\nStack is empty.\n");
return;
}
NODE *s = top;
printf("\nDeleted Element is %d\n", top->data);
top = top->link;
free(s);
if (top == NULL) {
start = NULL;
}
}
void display() {
if (top == NULL) {
printf("\nStack is empty.\n");
return;
}
printf("\nStack elements are:");
NODE *display = top;
while (display != NULL) {
printf("\n%d", display->data);
display = display->link;
}
printf("\n");
}
int main() {
int no, item;
char c;
printf("\n\tPROGRAM TO INSERT, DELETE AND DISPLAY ELEMENTS TO STACK USING LINKED LIST");
printf("\n\t.......................................................\n");
do {
printf("\t\t\t\tMENU\n");
printf("\t\t1. INSERT\n\t\t2. DELETE\n\t\t3. DISPLAY\n\t\t4. EXIT\n\t\tEnter your choice: ");
scanf("%d", &no);
switch (no) {
case 1:
printf("\nEnter the element: ");
scanf("%d", &item);
push(item);
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf("\nInvalid choice. Please enter a valid option.\n");
}
printf("\nDo you want to continue (y/n): ");
scanf(" %c", &c);
} while (c == 'y' || c == 'Y');
return 0;
}