0% found this document useful (0 votes)
15 views2 pages

C Stack Implementation in C Language

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views2 pages

C Stack Implementation in C Language

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

#include<stdio.

h>
#include<stdlib.h>
typedef struct node{
int data;
struct node *next;
}node;
typedef struct{
node *top;
} stack;
void push(stack *s,int element){
node* new_node=(node*)malloc(sizeof(node));
if(new_node==NULL){
printf("memory is not allocated");
}
else{
new_node->data=element;
new_node->next=NULL;
if(s->top){
new_node->next=s->top;
}
s->top=new_node;
printf("the element inserted is %d\n",element);
}
}
void pop(stack *s){
if(s->top==NULL){
printf("stack is empty\n");
return;
}
node *temp=s->top;
s->top=s->top->next;
printf("%d is deleted\n",temp->data);
free(temp);
}
void display(stack *s){
if(s->top==NULL){
printf("stack is empty\n");
return;
}
node *temp=s->top;
while(temp!=NULL){
printf("%d ",temp->data);
temp=temp->next;
}
printf("\n");
}
int main(){
stack s=(stack)malloc(sizeof(stack));
s->top=NULL;
int element,ch;
while(1){
printf("enter 1 to push\nenter 2 to pop\nenter 3 to display\nenter 4 to
exit\n");
scanf("%d",&ch);
switch(ch){
case 1:printf("enter the element to be inserted ");
scanf("%d",&element);
push(s,element);
break;
case 2:pop(s);
break;
case 3:display(s);
break;
case 4:exit(0);break;
}
}
return 0;
}

You might also like