• 为了保证你在浏览本网站时有着更好的体验,建议使用类似Chrome、Firefox之类的浏览器~~
    • 如果你喜欢本站的内容何不Ctrl+D收藏一下呢,与大家一起分享各种编程知识~
    • 本网站研究机器学习、计算机视觉、模式识别~当然不局限于此,生命在于折腾,何不年轻时多折腾一下

21. Merge Two Sorted Lists

leetcode admin 7个月前 (02-11) 293次浏览 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

解法

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

class Solution:
    def mergeTwoLists(self, l1: 'ListNode', l2: 'ListNode') -> 'ListNode':
        
        newHead = ListNode(None)
        pointer = newHead

        while l1 or l2:            
            if l1 is not None and (l2 is None or l1.val <= l2.val):
                pointer.next = l1
                l1 = l1.next
            else:
                pointer.next = l2
                l2 = l2.next

            pointer = pointer.next

        return newHead.next
            
            
                
            
        

Deeplearn, 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明21. Merge Two Sorted Lists
喜欢 (0)
admin
关于作者:
互联网行业码农一枚/业余铲屎官/数码影音爱好者/二次元

您必须 登录 才能发表评论!