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.
# Enter your code here. Read input from STDIN. Print output to STDOUTclassQueue:#CostlyDeQueue# Queue using two stacks with costly deQueue()def__init__(self):self.s1=[]#Stacksself.s2=[]#Stacks# Note that for Stacks, we can either do append() or pop()# EnQueue item to the queuedefenQueue(self,x):self.s1.append(x)# DeQueue item from the queuedefdeQueue(self):# if s2 is empty and s1 has elementsifnotself.s2:whileself.s1:self.s2.append(self.s1.pop())returnself.s2.pop()ifself.s2elseNonedefpeek(self):ifnotself.s2:whileself.s1:self.s2.append(self.s1.pop())returnself.s2[-1]ifself.s2elseNonequeue=Queue()foriinrange(int(input())):query=input().split(" ")ifquery[0]=="1":#enqueuequeue.enQueue(query[1])elifquery[0]=="2":#pop(dequeuefrontelement)queue.deQueue()elifquery[0]=="3":#printprint(queue.peek())else:print("ERROR!")#Shouldneverreachhere
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 →
Python Solution