LeetCode 21. 合并两个有序链表 Merge Two Sorted Lists

120 阅读1分钟

Table of Contents

一、中文版

二、英文版

三、My answer

四、解题报告


一、中文版

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

示例:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

二、英文版

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

来源:力扣(LeetCode)
链接:leetcode-cn.com/problems/me…
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

三、My answer

# 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:
        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
        if l1:
            head.next = l1
            
            
        if l2:
            head.next = l2
        
        return dummy.next

四、解题报告

此题用来熟悉 Python 链表的写法很好。

从头开始遍历两个链表,比较两个头结点的大小,将小的放入结果链表中。

剩下没遍历结束的 l1 或 l2,就直接拼接在结果链表中即可。