美文网首页leetcode题解
【Leetcode】21—Merge Two Sorted Li

【Leetcode】21—Merge Two Sorted Li

作者: Gaoyt__ | 来源:发表于2019-07-12 00:13 被阅读0次
    一、题目描述

    将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
    示例:

    输入:1->2->4, 1->3->4
    输出:1->1->2->3->4->4
    
    二、代码实现
    # 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
            """
            newHead = ListNode(-1)
            p = newHead
            while l1 and l2:
                if l1.val < l2.val:
                    p.next = l1
                    l1 = l1.next
                else:
                    p.next = l2
                    l2 = l2.next
                p = p.next
            if l1: p.next = l1
            if l2: p.next = l2
            
            return newHead.next
    

    相关文章

      网友评论

        本文标题:【Leetcode】21—Merge Two Sorted Li

        本文链接:https://www.haomeiwen.com/subject/hmhskctx.html