将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
代码1:递归法
def mergeTwoLists(self,l1,l2):
if l1 is None: #如果为空
return l2 #返回链表l2
elif l2 is None: #如果l2为空
return l1 #返回l1
elif l1.val < l2.val: #如果链表1上的值比链表2上的值小
l1.next = self.mergeTwoLists(l1.next,l2) #那么把当前小的
#结点的后继指向作为剩下结点的头结点
return l1
else:
l2.next = self.mergeTwoLists(l1,l2.next) #同上
return l2
通常做法:
def mergeTwoLists(self,l1,l2):
#maintain an unchanging reference to node ahead of the return node.
prehead = ListNode(-1)
prev = prehead #prev为游动指针
while l1 and l2:
if l1.val <= l2.val:
prev.next = l1 #游动指针为后继结点为l1
l1 = l1.next #l1指针移到下一个位置
else:
prev.next = l2
l2 = l2.next
prev = prev.next #游动指针往后移动一个位置
#exactly one of l1 and l2 can be non-null at this point, so connect
#the non-null list to the end of merged list.
prev.next = l1 if l1 is not None else l2
return prehead.next