553 views

2 Answers

0 votes
0 votes

Method 1 (By making enQueue operation costly) 

This method makes sure that oldest entered element is always at the top of stack 1, so that deQueue operation just pops from stack1. To put the element at top of stack1, stack2 is used.

enQueue(q, x):

While stack1 is not empty, push everything from stack1 to stack2.
Push x to stack1 (assuming size of stacks is unlimited).
Push everything back to stack1.
Here time complexity will be O(n)

deQueue(q):

If stack1 is empty then error
Pop an item from stack1 and return it
Here time complexity will be O(1)

Method 2 (By making deQueue operation costly)

In this method, 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).
Here time complexity will be O(1)

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.
Here time complexity will be O(n)

 

Ref: https://www.geeksforgeeks.org/queue-using-stacks/

0 votes
0 votes

Let us consider the queue $Q$ with operations $enqueue(Q, data)$ and $dequeue(Q)$. Stack $S1$ and $S2$ with operations $push(S1, data)$, $pop(S1)$ and $push(S2, data)$, $pop(S2)$.

Now the implementation for $enqueue(Q, data)$ for queue $Q$ can mimic by using following step:

// directly push the enqueued data into the first stack
// TimeComplexity: O(1)
enqueue(Q, data) {
    push(S1, data)
}

For $dequeue(Q)$ operation following steps required:

// Time Complexity O(n)
dequeue(Q):
    // If S2 is not empty pop from S2
    if S2 is not empty:
        data = pop(S2)
        return data
    // Else trasfer all elements from S1 to S2 then pop from S2.
    else: // S2 is empty
        Transfer all elements from S1 to S2
        data = pop(S2)
        return data
queue_with_2stacks
Representation of Implementation of Queue using 2 stacks

Related questions

0 votes
0 votes
1 answer
2
akash.dinkar12 asked Jun 28, 2019
554 views
Rewrite ENQUEUE and DEQUEUE to detect underflow and overflow of a queue.
4 votes
4 votes
2 answers
4
akash.dinkar12 asked Jun 28, 2019
1,288 views
Show how to implement a stack using two queues. Analyze the running time of the stack operations.