今天学习了栈和队列两种基本的数据结构, 之前对这两种结构的理解只是在应用层面。队列是 First-in-first-out。栈是 Last-in-first-out.
队列或者栈的底层都可以通过 deque (双向队列)来实现。 栈提供push 和 pop 等等接口,所有元素必须符合先进后出规则,所以栈不提供走访功能,也不提供迭代器(iterator)。 所以STL中栈往往不被归类为容器,而被归类为container adapter(容器适配器)。另外python 是没有内置的栈这种数据结构的, 但是可以直接用 deque, 封住一端数据的进出实现栈的功能。
两个问题比较基础, 分别是用两个栈实现 queue 和用两个queue实现栈。
232.用栈实现队列
from collections import deque
class MyQueue:
def __init__(self):
self.in_stack = deque()
self.out_stack = deque()
def push(self, x: int) -> None:
self.in_stack.append(x)
def pop(self) -> int:
if self.empty():
raise ValueError('Can not pop elements from empty queue!')
if len(self.out_stack) == 0:
while len(self.in_stack):
num = self.in_stack.pop()
self.out_stack.append(num)
return self.out_stack.pop()
def peek(self) -> int:
num = self.pop()
self.out_stack.append(num)
return num
def empty(self) -> bool:
return not bool(len(self.in_stack) + len(self.out_stack))
# 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. 用队列实现栈
from queue import Queue
class MyStack:
def __init__(self):
# tmp_queue for pop/top element
self.stock_queue = Queue()
self.tmp_queue = Queue()
def push(self, x: int) -> None:
self.stock_queue.put(x)
def pop(self) -> int:
if self.stock_queue.empty():
raise ValueError('Can not pop from empty stack!')
ans = -1
while not self.stock_queue.empty():
ans = self.stock_queue.get()
if not self.stock_queue.empty():
self.tmp_queue.put(ans)
while not self.tmp_queue.empty():
_tmp = self.tmp_queue.get()
self.stock_queue.put(_tmp)
return ans
def top(self) -> int:
ans = self.pop()
self.stock_queue.put(ans)
return ans
def empty(self) -> bool:
return self.stock_queue.empty()
# 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()