Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
解答:两个指针i,j,分别指向链表1和链表2的头部,循环遍历链表,比较指针所指的值,若i指针的值小于j指针,并把指针i右移,继续和链表2对比,以此类推,可用递归实现
class Solution(object):
def mergeTwoLists(self, l1, l2):
if not l1 or not l2: # 如果两个链表有一个为空,直接返回另一个链表即可
return l1 or l2
if l1.val < l2.val: # 若链表l1的值小于l2
l1.next = self.mergeTwoLists(l1.next, l2) # l1指针右移,继续和l2指针所指的数比较
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2