Implementation of Stack using Linked List in C
Stack With Linked List
We had seen how to implement simple stack using array.
If you had not seen, just go through it once Stack with Array
Now, let us see the implementation of stack using linked list.
#include <stdio.h>
#include <conio.h>
#include
void push();
void pop();
void display();
typedef struct node
{
int data;
struct node *link;
}node;
node *init, *new1, *temp;
int ch,flag=1;
void main()
{
clrscr();
while(1)
{
printf("\n1). Push");
printf("\n2). Pop");
printf("\n3). Display");
printf("\n4). Exit");
printf("\nEnter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf("Enter the correct choice");
break;
}
}
}
void display()
{
struct node *temp;
if(init==NULL)
{
printf("\nList is empty\n");
return;
}
else
{
temp=init;
printf("\nThe List elements are:\n");
while(temp!=NULL)
{
printf("%d\t",temp->data );
temp=temp->link;
}
}
}
void push()
{
struct node *temp,*ptr;
temp=(struct node *)malloc(sizeof(struct node));
if(temp==NULL)
{
printf("\nOut of Memory Space:\n");
exit(0);
}
printf("Enter value for first two node.");
if(flag==1)
{
printf("\nEnter the data value for the node:\t");
scanf("%d",&temp->data);
temp->link=NULL;
if(init==NULL)
{
init=temp;
}
else
{
temp=init;
while(temp->link!=NULL)
{
temp=temp->link;
}
temp->link=new1;
}
flag++;
}
if(flag!=1)
{
struct node *temp;
temp=(struct node *)malloc(sizeof(struct node));
if(temp==NULL)
{
printf("\nOut of Memory Space:\n");
return;
}
printf("\nEnter the data value for the node:\t" );
scanf("%d",&temp->data);
temp->link =NULL;
if(init==NULL)
{
init=temp;
}
else
{
temp->link=init;
init=temp;
}
}
}
void pop()
{
if(init==NULL)
{
printf("\nList is Empty:\n");
return;
}
else
{
temp=init;
init=init->link ;
printf("\nThe deleted element is :%d\t",temp->data);
free(temp);
}
}
Comments
Post a Comment