码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-05-02 11:49:36      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:bsp   ext   lis   class   out   return   put   linked   sts   

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

 

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

标签:bsp   ext   lis   class   out   return   put   linked   sts   

原文地址:https://www.cnblogs.com/Johnsonxiong/p/10801797.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!