您的位置:首页 > 编程语言 > Python开发

21. Merge Two Sorted Lists-Python

2017-07-04 21:05 309 查看


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.

思路



递归最容易实现,根据l1和l2头节点数据域的大小,决定合并后链表的头结点,这样问题的规模减1,递归直到满足其中的3个返回条件的中的一个:

if l1==None and l2==None:

return None

if l1==None:

return l2

if l2==None:

return l1

代码实现

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1==None and l2==None:
return None
if l1==None:
return l2
if l2==None:
return l1
if l1.val<=l2.val:
l1.next=self.mergeTwoLists(l1.next,l2)
return l1
else:
l2.next=self.mergeTwoLists(l1,l2.next)
return l2
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: