C Program to Implement Stack Operations using Singly Linked List.
⦁ Stack is a linear data structure in which the operations are performed based on LIFO principle.
⦁ Single linked list is a sequence of elements in which every element has link to its next element in the sequence.
⦁ The individual element is called as Node. Every node contains 2 fields data and next.
⦁ The data field is used to store actual value of that node and next field is used to store the address of the next node in the sequence.
--------------------------------------------------------------------------------------------------------------------------
#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<stdlib.h>
#include<alloc.h>
void Push(int,node**);
void Display(node **);
int Pop(node**);
int Sempty(node *);
typedef struct stack
{
int data;
struct stack *next;
}node;
void main( )
{
node *top;
int data,item,choice;
char ans,ch;
clrscr( );
top = NULL;
printf("\n Stack using Linked List : nn");
do{
printf("\n The main menu");
printf("\n1.Push\n2.Pop\n3.Display\n4.Exit");
printf("\n Enter Your Choice");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\n Enter Data");
scanf("%d",&data);
push(data,&top);
break;
case 2:
if(Sempty(top))
printf("\n Stack underflow!");
else
{
item = Pop(&top);
printf("\n The popped node is %d",ite,m);
}
break;
case 3:
Display(&top);
break;
case 4:
printf("\n Do You want to Quit?(y/n)");
ch = getche( );
if(ch =='y');
exit(0);
else
break;
}
printf("\n Do you want to continue?");
ans = getche( );
getch( );
clrscr( );
}
while(ans =='y' || ans == 'y');
getch( );
}
void Push(int item, node **top)
{
node *New;
node *get_node(int);
New = get_node(Item);
New->next = *top;
*top = New;
}
node *get_node(int item)
{
node *temp;
temp = (node *)malloc(sizeof(node));
if(temp == NULL)
printf("\n Memory cannot be allowed");
temp->data = item;
temp->next = NULL;
return temp;
}
int Sempty(node *temp)
{
if(temp == NULL)
return 1;
else
return 0;
}
int Pop(node **top)
{
int item;
node *temp;
item = (*top)->data;
temp = *top;
*top = (*top)->next;
free(temp);
return(item);
}
void Display(node **head)
{
node *temp;
temp = *head;
if(Sempty(temp))
printf("\n The stack is empty!");
else
{
while(temp! = NULL)
{
printf("%d\n",temp->data_);
temp = temp->next;
}
}
getch( );
}
--------------------------------------------------------------------------------------------------------------------------
Output
--------------------------------------------------------------------------------------------------------------------------
Displays Stack Operations.
EmoticonEmoticon