剣指offer面接問題17----2つの並べ替えのチェーン時計を合併する

1064 ワード

タイトル:2つの単調に増加するチェーンテーブルを入力して、2つのチェーンテーブルの合成後のチェーンテーブルを出力して、もちろん私たちは合成後のチェーンテーブルが単調で減少しない規則を満たす必要があります.例えば、入力[1,3,5],[2,4,6],出力[1,2,3,4,5,6]
考え方:両方のチェーンテーブルがインクリメントされているため、2つのチェーンテーブルの最初の要素を順番に比較し、どのチェーンテーブルの最初の要素が小さい場合は、結果チェーンテーブルに挿入し、ノードを元のチェーンテーブルから削除します.上記の操作を1つのチェーンテーブルが空になるまで順次繰り返し、別のチェーンテーブルを結果チェーンテーブルのnext要素とする
Pythonコードは以下の通りです.
# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    #        
    def Merge(self, pHead1, pHead2):
        # write code here
        res = head = ListNode(0)
    
        while pHead1 and pHead2:
            if pHead1.val <= pHead2.val:
                head.next = pHead1
              pHead1 = pHead1.next
            elif pHead1.val > pHead2.val:
                head.next = pHead2
                pHead2 = pHead2.next
            head = head.next
        
        if not pHead1:
            head.next = pHead2
        if not pHead2:
            head.next = pHead1
        
        return res.next