我已经实现了合并排序链表的功能,但是最后一个节点没有合并。如果我将current.next设置为l2,则会出现无限循环。如果我删除它的作品,但没有最后一个节点附加到新列表。我在做什么错了?
def merge(self,l1,l2):
if l1.val < l2.val:
current = l1
l2 = l2
else:
current = l2
l2 = l1
while(current != None):
if current.next == None and l2 != None:
#current.next = l2 infinite loop if I include this
elif current.next.val > l2.val:
temp = current.next
current.next = l2
l2 = temp
current = current.next
self.printList(current)
列表1:5 7 16
列表2:2 4 6 8 10
预期2 4 5 6 7 8 10 16
,当前结果2 4 5 6 7 8 10
答案 0 :(得分:0)
取自公认的解决方案here,该算法可解决您的问题:
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
答案 1 :(得分:0)
我没有检查极端情况,这是一个解决方法:
def merge(self,l1,l2):
if l1.val < l2.val:
current = l1
l2 = l2
else:
current = l2
l2 = l1
while(current != None):
if current.next == None and l2 != None:
current.next = l2
l2 = None
elif current.next != None and l2 != None and current.next.val > l2.val:
temp = current.next
current.next = l2
l2 = temp
current = current.next