python中的列表可以完美的模拟栈的操作,append, pop
LeetCode 232. 用栈实现队列
力扣题目链接
本题使用两个栈,一个入栈一个出栈,需要注意的是,pop时若出栈不为空,直接在出栈里pop,如果出栈为空,需要将入栈中所有元素移动到出栈中,再pop即可。
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:
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()
LeetCode 225. 用队列实现栈
力扣题目链接
本题也很简单,实际用一个队列即可实现。
class MyStack:
def __init__(self):
self.queue = []
def push(self, x: int) -> None:
self.queue.append(x)
def pop(self) -> int:
if self.empty():
return None
for i in range(len(self.queue) - 1):
temp = self.queue.pop()
self.queue.append(temp)
return self.queue.pop()
def top(self) -> int:
if self.empty():
return None
ans = self.pop()
self.queue.append(ans)
return ans
def empty(self) -> bool:
return not self.queue
# 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()
今日毕!