Queue using Two Stacks
In this class, We discuss Queue using Two Stacks.
The reader can complete a competitive coding course to crack product development companies. Click Here.
Question:
Implement a queue using two stacks.
We need to do queue operations using two stacks.
Queue works in the first in, first out model.
Whenever we do enqueue operation, we insert the element at the end.
We need to remove the element from the front whenever we do a dequeue operation.
The two operations, enqueue and dequeue, are to be implemented using two stacks.
Logic:
The step-by-step logic is explained in the video.
Code:
def Push(x,s1,s2):
while len(s1) != 0:
s2.append(s1[-1])
s1.pop()
s1.append(x)
while len(s2) != 0:
s1.append(s2[-1])
s2.pop()
def Pop(s1,s2):
if len(s1) == 0:
return -1
x = s1[-1]
s1.pop()
return x
s1=[]
s2=[]
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,s1,s2)
print("element inserted")
elif(x==2):
z=Pop(s1,s2)
print(z)
elif(x==3):
break;
else:
print("wrong option")
Link for playlists:
/ @learningmonkey
Link for our website: https://learningmonkey.in
Follow us on Facebook @ / learningmonkey
Follow us on Instagram @ / learningmonkey1
Follow us on Twitter @ / _learningmonkey
Mail us @ [email protected]