一、今日任务
二、理论基础
队列:先进先出
栈:先进后出
三、用栈实现队列
3.1 题目:232. 用栈实现队列
3.2 解题过程
首先确定python语言要用list代替栈。这个约定,从尾进尾出。
class MyQueue(object):
def __init__(self):
self.stacka = []
self.stackb = []
def push(self, x):
"""
:type x: int
:rtype: None
"""
self.stacka.append(x)
def pop(self):
"""
:rtype: int
"""
index = len(self.stacka)-1
while index >= 0:
self.stackb.append(self.stacka[index])
index -= 1
self.stacka = []
rnum = self.stackb[len(self.stackb)-1]
self.stackb.pop()
index = len(self.stackb)-1
while index >= 0:
self.stacka.append(self.stackb[index])
index -= 1
self.stackb = []
return rnum
def peek(self):
"""
:rtype: int
"""
index = len(self.stacka)-1
while index >= 0:
self.stackb.append(self.stacka[index])
index -= 1
rnum = self.stackb[len(self.stackb) - 1]
self.stackb = []
return rnum
def empty(self):
"""
:rtype: bool
"""
if len(self.stacka) == 0:
return True
return False
3.3 阅读材料改进
根据随想录解答自己以下几个地方要重点借鉴。
class MyQueue:
def __init__(self):
"""
in主要负责push,out主要负责pop
"""
self.stack_in = []
self.stack_out = []
def push(self, x: int) -> None:
"""
有新元素进来,就往in里面push
"""
self.stack_in.append(x)
def pop(self) -> int:
"""
Removes the element from in front of queue and returns that element.
"""
if self.empty():
return None # 自己没有考虑到的。
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:
"""
Get the front element.
"""
ans = self.pop()
self.stack_out.append(ans)
return ans # 比自己的思路简单很多。
def empty(self) -> bool:
"""
只要in或者out有元素,说明队列不为空
"""
return not (self.stack_in or self.stack_out) #好妙的写法。
四、用队列实现栈
4.1 题目:225. 用队列实现栈
4.2 解题过程
根据随想录提示使用deque这个数据结构来写。定appendleft和pop作为先进后出的操作。
首先使用两个队列模拟栈。
import collections
class MyStack(object):
def __init__(self):
self.queue_in = collections.deque()
self.queue_out = collections.deque()
def push(self, x):
"""
:type x: int
:rtype: None
"""
self.queue_in.appendleft(x)
def pop(self):
"""
:rtype: int
"""
if self.empty():
return None
if len(self.queue_out) > 0:
ans = self.queue_out.pop()
return ans
else:
while len(self.queue_in) > 1:
self.queue_out.appendleft(self.queue_in.pop())
ans = self.queue_in.pop()
while self.queue_out:
self.queue_in.appendleft(self.queue_out.pop())
return ans
def top(self):
"""
:rtype: int
"""
ans = self.pop()
self.push(ans)
return ans
def empty(self):
"""
:rtype: bool
"""
return not (self.queue_in or self.queue_out)
尝试使用一个队列模仿。增加一个长度计数。
class MyStack(object):
def __init__(self):
self.queue = collections.deque()
self.length = 0
def push(self, x):
"""
:type x: int
:rtype: None
"""
self.queue.appendleft(x)
self.length += 1
def pop(self):
"""
:rtype: int
"""
if self.empty():
return None
temp = self.length
while temp > 1:
self.queue.appendleft(self.queue.pop())
temp -= 1
ans = self.queue.pop()
self.length -= 1
return ans
def top(self):
"""
:rtype: int
"""
ans = self.pop()
self.push(ans)
return ans
def empty(self):
"""
:rtype: bool
"""
return not self.queue
4.3 阅读材料改进
解题过程已有借鉴。