栈与队列232|225
232用栈实现队列
class MyQueue: def __init__(self): self.listin = [] self.listout = [] def push(self, x: int) -> None: self.listin.append(x) def pop(self) -> int: if not self.listin and not self.listout: return None if self.listout: return self.listout.pop() else: while self.listin: element = self.listin.pop() self.listout.append(element) return self.listout.pop() def peek(self) -> int: element = self.pop() self.listout.append(element) return element def empty(self) -> bool: if not self.listin and not self.listout: return True else: return False # Your MyQueue object will be instantiated and called as such: # obj = MyQueue() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.peek() # param_4 = obj.empty()
225用队列实现栈
class MyStack: def __init__(self): self.myque = deque() def push(self, x: int) -> None: self.myque.append(x) def pop(self) -> int: if not self.myque: return None for i in range(len(self.myque) - 1): self.myque.append(self.myque.popleft()) return self.myque.popleft() def top(self) -> int: if not self.myque: return None element = self.pop() self.myque.append(element) return element def empty(self) -> bool: return not self.myque # Your MyStack object will be instantiated and called as such: # obj = MyStack() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.top() # param_4 = obj.empty()