Leetcode 21. 合并两个有序链表

题目描述

合并两个升序列表,示例:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

解决方法

1.  递归:

class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: if l1 is None: return l2 elif l2 is None: return l1 elif l1.val < l2.val: l1.next = self.mergeTwoLists(l1.next, l2) return l1 else: l2.next = self.mergeTwoLists(l1, l2.next)
       return l2

2. 暴力解法

设置头节点,使用next,不断比较两个链表中的数值大小,进行合并

def mergeTwoLists(self, l1, l2):
    prenode = ListNode(-1)
    pre = prenode
    while l1 and l2:
        if l1.val <= l2.val:
            pre.next = l1
            l1 = l1.next
        else:
            pre.next = l2
            l2 = l2.next            
        pre = pre.next
    # 当l1、l2长度不同时直接加入到链表最后位置
    pre.next = l1 if l1 is not None else l2
    return prenode.next

全部代码

代码已通过测试

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        if l1 is None:
            return l2
        elif l2 is None:
            return l1
        elif l1.val < l2.val:
            l1.next = self.mergeTwoLists(l1.next, l2)
            return l1
        else:
            l2.next = self.mergeTwoLists(l1, l2.next)
            return l2

    def getSort(self, list):
        if list:
            node = ListNode(list.pop(0))
            node.next = self.getSort(list)
            return node

if __name__ == '__main__':
    list1 = [1, 2, 4]
    list2 = [1, 3, 4]
    list1 =Solution().getSort(list1)
    list2 =Solution().getSort(list2)
    final = Solution().mergeTwoLists(list1,list2)
    while final:
        print(final.val, end=" ")
        final = final.next

 

posted @ 2020-05-02 14:42  如鹿~  阅读(132)  评论(0编辑  收藏  举报