Stack using two queues

Last updated: 29th Aug, 2020

                 

Problem Statment

Implement a Stack using two queues q1 and q2.

Input Format
push(20) push(4) pop() push(7) pop()

Output Format
4 7

Explanation
push(20) : the stack will be {20}
push(4) : the stack will be {20 4}
pop()  : poped element will be 4 the stack will be {20}
push(7) : the stack will be {20 7}
pop()  : poped element will be 7
Approach :

1. Create two queue (q1 , q2) 2. Enqueue the elements to the front of q1. 3. Pop operation to dequeue from q1 4. q2 is used to enqueue at the front of q1. 5. Return the popped element

Python Code

def push(x):
    global q1
    global q2   
    # append value in the queue2
    q2.append(x)
    while len(q1):
        q2.append(q1[0]) # insert at back of queue2
        q1.pop(0) # remove top of queue1
    # transfers all elements from queue2 to queue1, by swapping the names
    q1 , q2 = q2 , q1
                                                
def pop():
    #return: the value of top of stack and pop from it.
    global q1
    global q2
    if len(q1):
        return q1.pop(0)
    else:
        return -1
                        
 
    #Driver's code
    import atexit
    import io
    import sys
                                    
    _INPUT_LINES = sys.stdin.read().splitlines()
    input = iter(_INPUT_LINES).__next__
    _OUTPUT_BUFFER = io.StringIO()
    sys.stdout = _OUTPUT_BUFFER
    @atexit.register
    def write():
        sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
       
    q1 = [] # first queue
    q2 = [] # second queue
    if __name__ == '__main__':
      a =[1 2 1 3 2 1 4 2]
      i = 0
      while i < len(a):
        if a[i] = =  1:
          push(a[i+1])
          i+=1
        else:
          print(pop(),end=" ")
          i+=1
      # clear both the queues
      q1 = []
      q2 = []
      print()