Write a Program to implement stack using Linked List.
code👇👇👇👇👇
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node* 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");
}
else{
struct Node* n =(struct Node*)malloc(sizeof(struct Node));
n->data = x;
n->next = top;
top = n;
return top;
}
}
int pop(struct Node** top){
if(isEmpty(*top)){
printf("Stack underflow\n");
}
else{
struct Node* n =*top;
*top = (*top)->next;
int x = n->data;
free(n);
printf("Popped element:%d\n",x);
return x;
}
}
void traverse(struct Node* top){
if(isEmpty(top)){
printf("Stack underflow\n");
return;
}
while(top!=NULL){
printf("Element: %d\n",top->data);
top = top->next;
}
}
int main(){
struct Node* top = NULL;
int choice,x;
while(choice!=4){
printf("\n1)Push\n2)Pop\n3)Show\n4)Exit");
printf("\n Enter your choice: ");
scanf("%d",&choice);
switch(choice){
case 1:
printf("Enter element:");
scanf("%d",&x);
top = push(top,x);
break;
case 2:
x = pop(&top);
break;
case 3:
traverse(top);
break;
case 4:
printf("Exiting...");
break;
default:
printf("Please enter valid choice");
};
}
return 0;
}
No comments:
Post a Comment