Stack Using Two Queues
In this class, We discuss Stack Using Two Queues.
The reader can complete a competitive coding course to crack product development companies. Click Here.
The reader has to complete a placement training course for basic coding skills. Click Here.
Question:
Implement a stack using two queues.
We need to implement stack operations using two queues.
The stack works as last in, first out.
But queue works as first in, first out.
Using two queues, we must write push and pop functions that work as a stack.
Logic:
The step-by-step explanation is provided in the video.
Code:
queue_1=[]
queue_2=[]
def push(x):
global queue_1
global queue_2
queue_2.append(x)
while (len(queue_1)!=0):
queue_2.append(queue_1.pop(0))
queue_1,queue_2 = queue_2,queue_1
def pop():
global queue_1
global queue_2
# code here
if len(queue_1)!=0:
return queue_1.pop(0)
else:
return -1
while(True):
x=int(input(“enter your option 1. Push 2. Pop 3. quit”))
if(x==1):
y=int(input(“enter the element to insert”))
push(y)
print(“element inserted”)
elif(x==2):
z=pop()
print(z)
elif(x==3):
break;
else:
print(“wrong option”)