Header Ads Widget

implementation of queue by using two stack.

 Code:-

// Online C compiler to run C program online
#include <stdio.h>
#include<stdlib.h>
#define max 5
int stack1[5];
int stack2[5];
int top1=-1,top2=-1;

// function for push the element into stack2
void push(int ele)
{
top2++;
stack2[top2]=ele;
}

// function for pop the element from the first stack1
int pop1()
{
int ele;
ele=stack1[top1];
top1--;
return ele;
}

// function for pop the element from second stack2
void pop2()
{
int ele;
if(top2==-1)
printf("Queue is empty\n");
ele=stack2[top2];
top2--;
printf("%d is deleted\n",ele);
}

// function for insert the element into queue
void enqueue()
{
if(top1==max-1)
printf("Queue is full\n");
else
{
int ele;
printf("Enter a number\n");
scanf("%d",&ele);
top1++;
stack1[top1]=ele;
}
}

// function for delete element from the stack2
void dequeue()
{
if(top2==-1)
{
while(top1!=-1)
{
push(pop1());
}
}
pop2();
}

// function for display the element
void display()
{
for(int i=top2;i>=0;i--)
printf("%d ",stack2[i]);
for(int i=0;i<=top1;i++)
printf("%d ",stack1[i]);
printf("\n");
}

// Driver program
int main() {
int ch;
printf("1. Insert the element in to queue\n");
printf("2. delete element from the queue\n");
printf("3. Display the element of the queue\n");
printf("4. exit\n");
while(1)
{
printf("Enter your choice \n");
scanf("%d",&ch);
switch(ch)
{
case 1: enqueue();
break;
case 2: dequeue();
break;
case 3: display();
break;
case 4: exit(0);
default: printf("Wrong key\n");
}
}
return 0;
}

Output:-


1. Insert the element in to queue
2. delete element from the queue
3. Display the element of the queue
4. exit
Enter your choice
1
Enter a number
1
Enter your choice
1
Enter a number
2
Enter your choice
1
Enter a number
3
Enter your choice
3
1 2 3
Enter your choice
2
1 is deleted
Enter your choice
3
2 3
Enter your choice
4




Post a Comment

0 Comments