代码改变世界

[LeetCode] 21. Merge Two Sorted Lists_Easy tag: Linked List

2019-05-02 10:49  Johnson_强生仔仔  阅读(255)  评论(0编辑  收藏  举报

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.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

这个题目思路就是用dummy node,然后依次判断是l1 小还是l2小,最后当一方是None的时候将另一方加在总list的最后即可。

Code

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def mergeTwoLists(self, l1, l2):
        dummy = ListNode(0)
        head = dummy
        while l1 and l2:
            if l1.val <= l2.val:
                head.next = l1
                l1 = l1.next
            else:
                head.next = l2
                l2 = l2.next
            head = head.next
        head.next = l1 if l1 else l2
        return dummy.next