232、用栈实现队列
class MyQueue(object):
def __init__(self):
self.stack_in = []
self.stack_out = []
def push(self, x):
"""
:type x: int
:rtype: None
"""
self.stack_in.append(x)
def pop(self):
"""
:rtype: int
"""
if not self.stack_out:
for _ in range(len(self.stack_in)):
self.stack_out.insert(0, self.stack_in.pop(-1))
res = self.stack_out.pop(0)
return res
def peek(self):
"""
:rtype: int
"""
ele = self.pop()
self.stack_out.insert(0, ele)
return ele
def empty(self):
"""
:rtype: bool
"""
return not (self.stack_in or self.stack_out)
python内置数据结构没有栈,需要自定义,底层实现结构可用list或者deque,用数组实现解决此题
225、用队列实现栈
from collections import deque
class MyStack(object):
def __init__(self):
self.q = deque()
def push(self, x):
"""
:type x: int
:rtype: None
"""
self.q.append(x)
def pop(self):
"""
:rtype: int
"""
n = len(self.q)
for _ in range(n-1):
self.q.append(self.q.popleft())
return self.q.popleft()
def top(self):
"""
:rtype: int
"""
ele = self.pop()
self.q.append(ele)
return ele
def empty(self):
"""
:rtype: bool
"""
return len(self.q) == 0
用双端队列实现该题,实际只用到了append方法和popleft方法,因此相当于单向队列实现
栈和队列理论基础:
栈和队列都是container adapter,底层实现有list,deque等,可插拔,一个是先入先出,一个后入先出,具体到python中,常用的有普通队列Queue,继承它的有后入先出队列,优先级队列,简单队列等,还有异步队列,双端队列