Leetcode 合并有序链表
解题思路
递归
如果有任何一方不为空,则停止递归。
否则较小结点的 next 指针指向其余结点的合并结果。
参考文档
代码
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1 == None: return l2
if l2 == None: return l1
if l1.val >= l2.val:
l2.next = self.mergeTwoLists(l2.next,l1)
return l2
else:
l1.next = self.mergeTwoLists(l1.next,l2)
return l1