LeetCode 21 [Merge Two Sorted List]

原题

将两个排序链表合并为一个新的排序链表

样例
给出 1->3->8->11->15->null,2->null,
返回 1->2->3->8->11->15->null。

解题思路

  • 基础链表操作,每次比较连个链表的头,把相对小的加入新链表

完整代码

# 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
        """
        dummy = ListNode(0)
        current = dummy
        while l1 != None and l2 != None:
            if l1.val < l2.val:
                current.next = l1
                l1 = l1.next
            else:
                current.next = l2
                l2 = l2.next
            current = current.next
        if l1 != None:
            current.next = l1
        else:
            current.next = l2
        return dummy.next

你可能感兴趣的:(LeetCode 21 [Merge Two Sorted List])