A similar question was asked earlier there, but the question here is the reverse of it, using two queues as a stack. The question...
Given two queues with their sta
Let S1 and S2 be the two Stacks to be used in the implementation of queues.
struct Stack
{ struct Queue *Q1;
struct Queue *Q2;
}
We make sure that one queue is empty always.
Push operation : Whichever queue is not empty, insert the element in it.
Push (struct Stack *S, int data)
{
if(isEmptyQueue(S->Q1)
EnQueue(S->Q2, data);
else EnQueue(S->Q1, data);
}
Time Complexity: O(1)
Pop Operation: Transfer n-1 elements to other queue and delete last from queue for performing pop operation.
`
int Pop(struct Stack *S){
int i, size;
if(IsEmptyQueue(S->Q2))
{
size=size(S->Q1);
i=0;
while(iQ2, Dequeue(S->Q1)) ;
i++;
}
return DeQueue(S->Q1);
}
else{
size=size(S->Q2);
while(iQ1, Dequeue(S->Q2)) ;
i++;
}
return DeQueue(S->Q2);
} }
Time Complexity: Running Time of pop Operation is O(n) as each time pop is called, we are transferring all the elements from one queue to oter.