leetcode(12)-2つの秩序チェーンテーブルをマージ
1406 ワード
2つの順序付きチェーンテーブルを新しい順序付きチェーンテーブルに結合して返します.新しいチェーンテーブルは、指定された2つのチェーンテーブルのすべてのノードを接合することによって構成されます.
リンク:https://leetcode-cn.com/problems/merge-two-sorted-lists/
リンク:https://leetcode-cn.com/problems/merge-two-sorted-lists/
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
head = ListNode(0) # head next
tail = head
while l1 or l2:
if l1 and l2:
if l1.val >=l2.val:
tail.next = ListNode(l2.val)
tail = tail.next
l2 = l2.next
else:
tail.next = ListNode(l1.val)
tail = tail.next
l1 = l1.next
else:
tail.next = l1 if l2 is None else l2
break
return head.next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
head = ListNode(0) # head next
tail = head
while l1 or l2:
if l1 and l2:
cmp = l1.val >=l2.val
tail.next = ListNode(l2.val) if cmp else ListNode(l1.val)
tail = tail.next
if cmp:
l2 = l2.next
else:
l1 = l1.next
else:
tail.next = l1 if l2 is None else l2
break
return head.next