Implementation of Stack with Singly Linked List : C Program
Here is the code for implementation of stack with singly linked list :
program code :
#include<stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *top=NULL;
void push(int d)
{
struct node *newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=d;
newnode->next=NULL;
if(top==NULL)
{
top=newnode;
}
else{
newnode->next=top;
top=newnode;
}
printf("\ndata %d has been pushed (entered to stack).",d);
}
void pop()
{
struct node *p,*temp=top;
if(temp=NULL)
{
printf("\nstack is empty.");
return;
}
p=top;
top=top->next;
free(p);
printf("\ntop element has been poped(deleted).");
}
void display()
{
struct node *p=top;
if(p==NULL)
{
printf("\nstack is empty.");
return;
}
printf("\nstack elements are : ");
while(p!= NULL)
{
printf("%d ",p->data);
p=p->next;
}
}
int main()
{
int el,op,exit=1;
do
{
printf("\nwhat you need : 1.push 2.pop 3.display 4.exit : ");
scanf("%d",&op);
switch(op)
{
case 1:
printf("enter the data : ");
scanf("%d",&el);
push(el);
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
exit=0;
break;
default:
printf("\n enter a valid key dude ");
}
}while(exit==1);
return 0;
}
output :
_----------_---------_-----------_/.
Happy coding.
Comment what you need.
Comments
Post a Comment