1.用栈实现队列
使用栈实现队列的下列操作:
push(x) -- 将一个元素放入队列的尾部。
pop() -- 从队列首部移除元素。
peek() -- 返回队列首部的元素。
empty() -- 返回队列是否为空。
class Solution:
def __init__(self):
self.s1 = []
self.s2 = []
def push(self,x):
self.s1.append(x)
def pop(self):
if self.empty():
return None
if self.s2:
return self.s2.pop()
else:
for _ in range(len(self.s1)):
self.s2.append(self.s1.pop())
return self.s2.pop()
def peek(self):
ans = self.pop()
self.s2.append(ans)
return ans
def empty(self):
return not (self.s1 or self.s2)
a = Solution()
print(a.push(1),a.push(2),a.peek(),a.pop(),a.empty())
2.用队列实现栈
使用队列实现栈的下列操作:
- push(x) -- 元素 x 入栈
- pop() -- 移除栈顶元素
- top() -- 获取栈顶元素
- empty() -- 返回栈是否为空