We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
classQueue:def__init__(self):self.stack1=[]#queueself.stack2=[]#dequeuedefenqueue(self,x):self.stack1.append(x)defdequeue(self):# stack 1 and stack 2 are emptyifnotself.stack1andnotself.stack2:returnNone# if stack 2 is empty, transfer stack 1 into stack 2ifnotself.stack2:whileself.stack1:self.stack2.append(self.stack1.pop())returnself.stack2.pop()defpeek(self):# If stack2 is empty, transfer elements from stack1ifnotself.stack2:whileself.stack1:self.stack2.append(self.stack1.pop())# Peek at the front element from stack2ifnotself.stack2:# If both stacks are empty, the queue is emptyreturnNonereturnself.stack2[-1]if__name__=='__main__':queue=Queue()n_queries=int(input())for_inrange(n_queries):query=input()if" "inquery:ifquery.split()[0]=="1":queue.enqueue(query.split()[1])else:ifquery=="2":queue.dequeue()ifquery=="3":print(queue.peek())
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Queue using Two Stacks
You are viewing a single comment's thread. Return to all comments →
This code works