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.
classMyStack:def__init__(self)->None:self.stk=[]defpush(self,item):self.stk.append(item)defpop(self):item=self.stk[-1]self.stk=self.stk[:-1]returnitemdefpeek(self):returnself.stk[-1]defis_empty(self):returnlen(self.stk)==0def__str__(self)->str:res=self.stkreturnstr(res)classMyQueueUsingStacks:def__init__(self)->None:self.stk_main=MyStack()self.stk_temp=MyStack()defenqueue(self,item):# remove all items from main stack to tempwhileself.stk_main.is_empty()==False:item_to_remove=self.stk_main.pop()self.stk_temp.push(item_to_remove)# now push new itemself.stk_main.push(item)# push all items again into main stack, first entered element will be on topwhileself.stk_temp.is_empty()==False:item_to_remove=self.stk_temp.pop()self.stk_main.push(item_to_remove)defdequeue(self):ifself.stk_main.is_empty():return"Empty Queue"returnself.stk_main.pop()defpeek(self):ifself.stk_main.is_empty():return"Empty Queue"returnself.stk_main.peek()defmain_driver():n=int(input())input_list=[]my_q=MyQueueUsingStacks()i=0whilei<n:inp=input_list.append(input())i+=1foriininput_list:ifi[0]=="1":item=int(i[2:])# enqueuemy_q.enqueue(item)ifi[0]=="2":# dequeuemy_q.dequeue()ifi[0]=="3":# print frontprint(my_q.peek())main_driver()
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