This program implements linked stack in c. A linked stack uses linked list to insert and delete elements in Last In First Out (LIFO) order. The items are entered and deleted form the top of the stack. The advantage of linked stack is that the items need not be entered in contiguous memory locations. This program implements push, pop and display operations in a linked stack. The stack uses the terms push and pop to denote insertion and deletion operation respectively.
Program
//Linked Stack
#include<stdio.h>
#include<conio.h>
struct node
{
int data;
struct node *next;
}*top=NULL,*p;
void main()
{
int ch,item;
printf("\n1.Push\n2.Pop\n3.Display\n4.Exit\n");
scanf("%d",&ch);
while(ch!=4)
{
switch(ch)
{
case 1:
printf("\nEnter the data to be inserted ");
scanf("%d",&item);
p=(struct node *)malloc(sizeof(struct node));
p->data=item;
p->next=top;
top=p;
break;
case 2:
if(top==NULL)
{
printf("\nStack is empty!!!\n");
}
else
{
p=top;
top=top->next;
free(p);
}
break;
case 3:
p=top;
if(p==NULL)
{
printf("Stack is empty!!!");
break;
}
printf("Stack Now is..\n\n");
while(p!=NULL)
{
printf("%d->",p->data);
p=p->next;
}
break;
}
printf("\n\n1.Push\n2.Pop\n3.Display\n4.Exit\n");
scanf("%d",&ch);
}
}
No comments:
Post a Comment