leetcode21_2つの順序付きチェーンテーブルを結合

4170 ワード

2つの昇順チェーンテーブルを新しい昇順チェーンテーブルに結合して返します.新しいチェーンテーブルは、指定された2つのチェーンテーブルのすべてのノードを接合することによって構成されます.
例:
入力:1->2->4、1->3->4出力:1->1->2->3->4->4
チェーンテーブルのヘッダheadは、最初のノードを指すポインタとして設計してもよいし、valがnoneのノードとして設計してもよい.ここでのチェーンテーブルは前者である.
統合ソートの考え方を採用する
# 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:
        if l1 is None:
            return l2
        elif l2 is None:
            return l1
        # head         ,         
        if l1.val < l2.val:
            head = l1
            l1 = l1.next
        else:
            head = l2
            l2 = l2.next
        cnode = head
        while l1 and l2:
            if l1.val < l2.val:
                cnode.next = l1
                l1 = l1.next
            else:
                cnode.next = l2
                l2 = l2.next
            cnode = cnode.next
        if l2:
            cnode.next = l2
        else:
            cnode.next = l1
            
        return head