【力扣题】题目描述:
栈:线性集合。后进先出。
队列:线性集合。先进先出。也有双端队列和循环队列。
【Python3】代码:
1、解题思路:两个队列。队列1存储元素,队列2辅助。元素从队尾进入队列2,已在队列1的元素依次从队头取出进入队列2,两队列互换,则队列1中队头的元素是后进入的元素。
知识点:collections.deque():队列容器。(注:queue模块用于线程通信,实现多生产者、多消费者队列)
collections.deque().append():往队尾添加元素。
collections.deque().popleft():从队头移除元素,并返回该元素。
补充:空队列,返回False。
class MyStack:
def __init__(self):
from collections import deque
self.aqueue = deque()
def push(self, x: int) -> None:
n = len(self.aqueue)
self.aqueue.append(x)
for _ in range(n):
self.aqueue.append(self.aqueue.popleft())
def pop(self) -> int:
return self.aqueue.popleft()
def top(self) -> int:
return self.aqueue[0]
def empty(self) -> bool:
return not self.aqueue
# 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()
2、解题思路:一个队列。元素从队尾进入队列,之前的元素依次从队头取出从队尾进入,则队列中队头的元素是后进入的元素。
知识点:a,b=b,a:即a和b的值互换。例如:a=1;b=2;a,b=b,a;则结果a=2,b=1。
class MyStack:
def __init__(self):
from collections import deque
self.aqueue_1 = deque()
self.aqueue_2 = deque()
def push(self, x: int) -> None:
self.aqueue_2.append(x)
# while self.aqueue_1:
for _ in range(len(self.aqueue_1)):
self.aqueue_2.append(self.aqueue_1.popleft())
self.aqueue_1,self.aqueue_2 = self.aqueue_2,self.aqueue_1
def pop(self) -> int:
return self.aqueue_1.popleft()
def top(self) -> int:
return self.aqueue_1[0]
def empty(self) -> bool:
return not self.aqueue_1
# 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()