stack using linked list
stack using linked list
h>
#include<stdlib.h>
struct node{
struct node *next;
int n;
};
struct node *first=NULL;
struct node *last;
struct node *current;
int push();
int pop();
int peek();
int display();
int main();
int push()
{
int n;
current=(struct node*)malloc(sizeof(struct node));
printf("Please enter n value");
scanf("%d",¤t->n);
if(first==NULL)
{
first=last=current;
last->next=NULL;
}
else
{
current->next=last;
last=current;
first=last;
}
}
int pop()
{
if(first==NULL)
printf("Stack is empty");
else
first=first->next;
}
int peek()
{
if(first==NULL)
printf("Stack is empty");
else
printf("The top element is %d",first->n);
}
int display()
{
if(first==NULL)
printf("Stack is empty");
else
{
current=first;
printf("The elements in the stack are \n");
while(current!=NULL)
{
printf("%d\t",current->n);
current=current->next;
}
}
}
int main()
{
int option,n;
while(1)
{
printf("\n1.Push\n2.Pop\n3.Peek\n4.Display\n5.Exit");
printf("\n\nPlease enter you choice of operation : ");
scanf("%d",&option);
switch(option)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
peek();
break;
case 4:
display();
break;
case 5:
return 0;
break;
default:
printf("Invalid choice entered");
}
}
}