代码随想录算法训练营Day 10|栈与队列Part01|232.用栈实现队列、225. 用队列实现栈
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 self.empty():
return None
if self.stack_out:
return self.stack_out.pop()
else:
for i in range(len(self.stack_in)):
num =self.stack_in.pop()
self.stack_out.append(num)
return self.stack_out.pop()
def peek(self):
"""
:rtype: int
"""
num = self.pop()
self.stack_out.append(num)
return num
def empty(self):
"""
:rtype: bool
"""
return not (self.stack_in or self.stack_out)
# 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()
二、本题总结
将一个栈当作输入栈,用于压入 push传入的数据;另一个栈当作输出栈,用于 pop 和peek 操作。
每次 pop 或 peek 时,若输出栈为空则将输入栈的全部数据依次弹出并压入输出栈,这样输出栈从栈顶往栈底的顺序就是队列从队首往队尾的顺序。
225. 用队列实现栈
一、解法
class MyStack(object):
def __init__(self):
self.que = deque()
def push(self, x):
"""
:type x: int
:rtype: None
"""
self.que.append(x)
def pop(self):
"""
:rtype: int
"""
if self.empty():
return None
# 把前面的排到后面去
for i in range(len(self.que)-1):
self.que.append(self.que.popleft())
return self.que.popleft()
def top(self):
"""
:rtype: int
"""
if self.empty():
return None
return self.que[-1]
def empty(self):
"""
:rtype: bool
"""
return not self.que
# 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()
二、本题总结
一个队列在模拟栈弹出元素的时候只要将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部,此时再去弹出元素就是栈的顺序了。