gpt4 book ai didi

python - 在python中将两个排序的链表合并为一个链表

转载 作者:太空宇宙 更新时间:2023-11-03 12:17:22 24 4
gpt4 key购买 nike

这是我的代码:

def merge_lists(head1, head2):
if head1 is None and head2 is None:
return None
if head1 is None:
return head2
if head2 is None:
return head1
if head1.value < head2.value:
temp = head1
else:
temp = head2
while head1 != None and head2 != None:
if head1.value < head2.value:
temp.next = head1
head1 = head1.next
else:
temp.next = head2
head2 = head2.next
if head1 is None:
temp.next = head2
else:
temp.next = head1
return temp
pass

这里的问题卡在死循环了,谁能告诉我是什么问题

例子是:

 assert [] == merge_lists([],[])
assert [1,2,3] == merge_lists([1,2,3], [])
assert [1,2,3] == merge_lists([], [1,2,3])
assert [1,1,2,2,3,3,4,5] == merge_lists([1,2,3], [1,2,3,4,5])

最佳答案

当前代码的问题在于它会导致临时节点的下一个之前从当前节点导航到下一个节点的副作用。当当前临时节点当前节点时,这是有问题的。

也就是说,想象一下这种情况:

temp = N
temp.next = N # which means N.next = N
N = N.next # but from above N = (N.next = N) -> N = N

有一个更正的版本,还有一些其他更新:

def merge_lists(head1, head2):
if head1 is None:
return head2
if head2 is None:
return head1

# create dummy node to avoid additional checks in loop
s = t = node()
while not (head1 is None or head2 is None):
if head1.value < head2.value:
# remember current low-node
c = head1
# follow ->next
head1 = head1.next
else:
# remember current low-node
c = head2
# follow ->next
head2 = head2.next

# only mutate the node AFTER we have followed ->next
t.next = c
# and make sure we also advance the temp
t = t.next

t.next = head1 or head2

# return tail of dummy node
return s.next

关于python - 在python中将两个排序的链表合并为一个链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22507197/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com