21.leetcode题目讲解(Python):合并两个有序链表

2018-09-29  本文已影响101人  夏山闻汐

题目如下:


题目

这道题比较简单,需要注意的是如果输入有空链表,那么直接返回非空链表。如果都为空链表那么返回空。思路为将两个链表都装入到一个list中,通过sorted进行排序,然后根据排序后的list返回新的链表,参考代码如下:

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


class Solution:
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if l1 is None and l2 is None:
            return None
        elif l1 is not None and l2 is None:
            return l1
        elif l2 is not None and l1 is None:
            return l2

        l = []
        while l1 is not None:
            l.append(l1.val)
            l1 = l1.next
        while l2 is not None:
            l.append(l2.val)
            l2 = l2.next

        l = sorted(l)
        new_l = ListNode(l[0])
        head_l = new_l
        for i in range(1,len(l)):
            new_l.next = ListNode(l[i])
            new_l = new_l.next
        new_l.next = None
        return head_l

ps:如果您有好的建议,欢迎交流 :-D,也欢迎访问我的个人博客:tundrazone.com

其他题目:
leetcode题目答案讲解汇总(Python版 持续更新)

源码地址:
https://github.com/jediL/LeetCodeByPython

上一篇 下一篇

猜你喜欢

热点阅读