我实现了
push
和 pop
函数——基于两个队列——如下:
from queue import Queue
def push(x):
# global declaration
global queue_1
global queue_2
# code here
if queue_1.empty() and queue_2.empty():
queue_1.put(x)
if queue_1.empty()==1 and queue_2.empty()==0:
queue_1.put(x)
while queue_2.empty()==0:
y=queue_2.get()
queue_1.put(y)
if queue_1.empty()==0 and queue_2.empty()==1:
queue_2.put(x)
while queue_1.empty()==0:
y=queue_1.get()
queue_2.put(y)
# Function to pop an element from stack using two queues.
def pop():
# global declaration
global queue_1
global queue_2
# code here
if queue_1.empty() and queue_2.empty():
return -1
if queue_1.empty()==1:
x=queue_2.get()
else:
x=queue_1.get()
return x
我尝试使用这样的概念:在某一时刻,一个队列将为空,我们将在该空队列中添加新元素,并从另一个队列获取所有元素,并将它们附加到具有新添加元素的队列中。这样,当我们弹出一个元素时,我们将首先获得最近添加的元素。
对于一些简单的测试用例,上面的代码仍然失败,如下所示:
queue_1 = Queue()
queue_2 = Queue()
push(1)
push(2)
assert pop() == 2
assert pop() == 1 # Assertion failed
我的错误在哪里?
不确定您真正想要实现什么,但您的代码比获得所需效果所需的更复杂。
你可以像这样简化它,你的断言将是正确的:
from queue import Queue
def pop(q1: Queue, q2: Queue)-> int:
if q1.empty():
if q2.empty():
return -1
return q2.get()
return q1.get()
def push(x: int, q1: Queue, q2: Queue):
if q1.empty():
q1.put(x)
while not q2.empty():
q1.put(q2.get())
else:
q2.put(x)
while not q1.empty():
q2.put(q1.get())
def main():
q1 = Queue()
q2 = Queue()
push(1, q1, q2)
push(2, q1, q2)
assert pop(q1, q2) == 2
assert pop(q1, q2) == 1