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
相关文章推荐
- leetcode_效率题解_[python/C++]_21. Merge Two Sorted Lists(合并2个有序链表)
- 21. Merge Two Sorted Lists leetcode Python 2016 new Season
- 21. Merge Two Sorted Lists [easy] (Python)
- 21. Merge Two Sorted Lists —— Python
- 21. Merge Two Sorted Lists && 23. Merge k Sorted Lists
- [LeetCode] 21. Merge Two Sorted Lists 解题思路
- 22. Merge k Sorted Lists Leetcode Python
- [LeetCode] 021. Merge Two Sorted Lists (Easy) (C++/Python)
- [leetcode]Merge k Sorted Lists @ Python [基础知识: heap]
- Leetcode 23. Merge k Sorted Lists(python)
- leetcode Merge K sorted Lists python
- [leetcode] 21. Merge Two Sorted Lists 解题报告
- [leetcode]Merge k Sorted Lists @ Python
- LeetCode 21 — Merge Two Sorted Lists(C++ Java Python)
- LeetCode 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- [leetcode]Merge Two Sorted Lists @ Python
- 【LeetCode with Python】 Merge Two Sorted Lists
- leetcode 【 Merge k Sorted Lists 】python 实现
- LeetCode 23 Merge k Sorted Lists (C,C++,Java,Python)