You are viewing a single comment's thread. Return to all comments →
class QueueUsingTwoStacks: def __init__(self): self.primary_stack = [] self.temp_stack = [] def enqueue(self, item): self.primary_stack.append(item) def dequeue(self): if self.is_empty(): return None if not self.temp_stack: while self.primary_stack: self.temp_stack.append(self.primary_stack.pop()) return self.temp_stack.pop() def peek(self): if self.is_empty(): return None if not self.temp_stack: while self.primary_stack: self.temp_stack.append(self.primary_stack.pop()) return self.temp_stack[-1] def is_empty(self): return len(self.primary_stack) == 0 and len(self.temp_stack) == 0 if __name__ == '__main__': queue = QueueUsingTwoStacks() Q = int(input()) queries = [] for _ in range(Q): queries.append(list(map(int, input().split()))) for query in queries: cmd = query[0] if cmd == 1: item = query[1] queue.enqueue(item) elif cmd == 2: queue.dequeue() else: print(queue.peek())
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 →