栈实现队列
代码语言:javascript复制class Queue:
def __init__(self):
self.s1 = []
self.s2 = []
def peek(self):
if not self.s2:
while self.s1:
self.s2.append(self.s1.pop())
return self.s2[-1]
def push(self, x):
self.s1.append(x)
def pop(self):
self.peek()
if not self.s2:
return None
self.s2.pop()
def empty(self):
return not self.s1 and not self.s2
queue = Queue()
queue.push(1)
queue.push(2)
queue.push(3)
print("s1:", queue.s1)
print("s2:", queue.s2)
t = queue.peek()
print(t)
print("s1:", queue.s1)
print("s2:", queue.s2)
queue.pop()
print("s1:", queue.s1)
print("s2:", queue.s2)
queue.push(4)
queue.push(5)
print("s1:", queue.s1)
print("s2:", queue.s2)
queue.pop()
print("s1:", queue.s1)
print("s2:", queue.s2)
t = queue.peek()
print(t)
print("s1:", queue.s1)
print("s2:", queue.s2)
结果: s1: [1, 2, 3] s2: [] 1 s1: [] s2: [3, 2, 1] s1: [] s2: [3, 2] s1: [4, 5] s2: [3, 2] s1: [4, 5] s2: [3] 3 s1: [4, 5] s2: [3]