目录
- 232.用栈实现队列
- 225. 用队列实现栈
232.用栈实现队列
链接
相当于用两个stack将队列的元素顺序颠倒了一遍。
class MyQueue:def __init__(self):self.stack_in = []self.stack_out = []def push(self, x: int) -> None:self.stack_in.append(x)def pop(self) -> int:if self.stack_out:return self.stack_out.pop()else:for i in range(len(self.stack_in)):self.stack_out.append(self.stack_in.pop())return self.stack_out.pop()def peek(self) -> int:res = self.pop()self.stack_out.append(res)return resdef empty(self) -> bool:return not(self.stack_in or self.stack_out)
225. 用队列实现栈
链接
class MyStack:def __init__(self):self.que = deque()def push(self, x: int) -> None:self.que.append(x)def pop(self) -> int:if self.empty():return Noneelse:for i in range(len(self.que) - 1):self.push(self.que.popleft())return self.que.popleft()def top(self) -> int:if self.empty():return Noneelse:return self.que[-1]def empty(self) -> bool:return len(self.que) == 0