一、栈与队列理论基础:
栈:后进先出
队列:先进先出
队列有push,pop,empty,peek操作:
①queue.push(1)
②queue.push(2)
③queue.peek() 返回队列首部元素
③queue.empty()返回队列是否为空
二、队列刷题:
1.leetcode题目 232 用栈实现队列(easy):
题目描述:
解决:
class MyQueue:
def __init__(self):
self.stack_in = []
self.stack_out = []
def push(self, x: int) -> None:
self.stack_in.append(x)
def pop(self) -> int:
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:
ans = self.pop()
self.stack_out.append(ans)
return ans
def empty(self) -> bool:
if len(self.stack_in)==0 and len(self.stack_out)==0:
return True
else:
return False
# 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()
2.leetcode题目 225 用队列实现栈(easy):
题目描述:225. 用队列实现栈 - 力扣(LeetCode)
解决:
class MyStack:
def __init__(self):
self.queue_in = deque()
self.queue_out = deque()
def push(self, x: int) -> None:
self.queue_in.append(x)
def pop(self) -> int:
if self.empty():
return None
for i in range(len(self.queue_in) - 1):
self.queue_out.append(self.queue_in.popleft())
self.queue_out,self.queue_in = self.queue_in,self.queue_out
return self.queue_out.popleft()
def top(self) -> int:
if self.empty():
return None
return self.queue_in[-1]
def empty(self) -> bool:
return not self.queue_in
# 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()