Queueusingstack C

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

Queue using two stacks code.

#include<stdio.h>
#include<stdlib.h>
struct stack{
int top;
int size;
int *arr;
}
int isFull(struct stack *stack)
{
if(stack->top==stack->size-1)
{
return 1;
}
else
{
return 0;
}
}
int isEmpty(struct stack *stack)
{
if(stack->top==-1)
{
return 1;
}
else
{
return 0;
}
}

void push(struct stack *stack,int data)


{
if(isFull(stack))
{
printf("Queue Overflow.");
}
else
{
stack->top++;
stack->arr[stack->top]=data;
}
}
int pop(struct stack *stack)
{
if(isEmpty(stack))
{
printf("Queue Underflow.");
}
else
{
int data=stack->arr[stack->top];
stack->top--;
return data;
}
}
void traversal(struct stack *stack)
{
for(int i=0;i<=stack->top;i++)
{
printf("%d ",stack->arr[i]);
}
printf("\n");
}
int main()
{
struct stack *s1;
s1=(struct stack*)malloc(sizeof(struct stack));
s1->top=-1;
s1->size=8; //lets say the queue size is 8.
s1->arr=(int*)malloc(sizeof(int)*s1->size);
struct stack *s2;
s2=(struct stack*)malloc(sizeof(struct stack));
s2->top=-1;
s2->size=8;
s2->arr=(int*)malloc(sizeof(int)*s2->size);
//made two stack *s.
while(1)//menu program to make queue using two stacks of size 8.
{
int a;
printf("*********MENU*******\n");
printf("Select one of the following options: \n");
printf("1.Enqueue.\n");
printf("2.Dequeue.\n");
printf("3.Traversal.\n");
printf("4.Exit.\n");
scanf("%d",&a);

switch (a)
{
case 1:
int data;
printf("Enter the data to be inserted.");
scanf("%d",&data);

if(isEmpty(s1))
{
push(s1,data);
}
else
{
while(!isEmpty(s1))
{
push(s2,pop(s1));
}
push(s1,data);
while(!isEmpty(s2))
{
push(s1,pop(s2));
}
}
break;
case 2:
printf("The element is popped out %d\n",pop(s1));
break;
case 3:
traversal(s1);
break;
case 4:
return 0;
default:
printf("why you failure");
break;
}
}
}

You might also like