You are viewing a single comment's thread. Return to all comments →
import sys class Stack: def __init__(self): self.container = [] def is_empty(self) -> bool: if len(self.container) == 0: return True return False def push(self, num) -> None: self.container.append(num) def pop(self) -> int: val = None if not self.is_empty(): val = self.container.pop() return val def top(self) -> int: val = None if not self.is_empty(): val = self.container[-1] return val class Queue: def __init__(self): self.secondary = Stack() self.primary = Stack() def enqueue(self, num) -> None: if self.primary.is_empty(): self.primary.push(num) else: while (not self.primary.is_empty()): self.secondary.push(self.primary.pop()) self.primary.push(num) while (not self.secondary.is_empty()): self.primary.push(self.secondary.pop()) def dequeue(self) -> int: if not self.primary.is_empty(): return self.primary.pop() return None def head(self) -> int: if not self.primary.is_empty(): return self.primary.top() return None queue = Queue() count = 0 for line in sys.stdin: if count == 0: no_of_inputs = int(line) elif count > no_of_inputs: break else: query = line.split() if int(query[0]) == 1: queue.enqueue(int(query[1])) elif int(query[0]) == 2: value = queue.dequeue() else: print(str(queue.head())) count += 1
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 →