/* C++ Program to Implement Queue Using Two Stacks
This is a C++ Program to implement queue using stacks. In this program, in en-queue operation, the new element is entered at the top of stack1. In de-queue operation, if stack2 is empty then all the elements are moved to stack2 and finally top of stack2 is returned.
enQueue(q, x)
1) Push x to stack1 (assuming size of stacks is unlimited).
deQueue(q)
1) If both stacks are empty then error.
2) If stack2 is empty
While stack1 is not empty, push everything from stack1 to stack2.
3) Pop the element from stack2 and return it. *//* Program to implement a queue using two stacks */#include<stdio.h>#include<stdlib.h>#include<iostream>usingnamespacestd;
structsNode
{int data;
structsNode *next;
};
voidpush(struct sNode** top_ref, int new_data);
intpop(struct sNode** top_ref);
structqueue
{structsNode *stack1;structsNode *stack2;
};
voidenQueue(struct queue *q, int x){
push(&q->stack1, x);
}
intdeQueue(struct queue *q){
int x;
if (q->stack1 == NULL && q->stack2 == NULL)
{
cout << "Queue is empty";
return0;
}
if (q->stack2 == NULL)
{
while (q->stack1 != NULL)
{
x = pop(&q->stack1);
push(&q->stack2, x);
}
}
x = pop(&q->stack2);
return x;
}
voidpush(struct sNode** top_ref, int new_data){
structsNode* new_node = (structsNode*) malloc(sizeof(structsNode));if (new_node == NULL)
{
cout << "Stack overflow \n";
return ;
}
new_node->data = new_data;
new_node->next = (*top_ref);
(*top_ref) = new_node;
}
intpop(struct sNode** top_ref){
int res;
structsNode *top;/*If stack is empty then error */if (*top_ref == NULL)
{
cout << "Stack overflow \n";
return0;
}
else
{
top = *top_ref;
res = top->data;
*top_ref = top->next;
free(top);
return res;
}
}
intmain(){
structqueue *q = (structqueue*) malloc(sizeof(structqueue));
q->stack1 = NULL;
q->stack2 = NULL;
enQueue(q, 4);
enQueue(q, 8);
enQueue(q, 3);
cout << deQueue(q) << " ";
cout << deQueue(q) << " ";
cout << deQueue(q) << " ";
cout << endl;
}
/*
Output :
4 8 3
*/
Comments