トピックは比較的単純です。
私の考えは、2つのリンクリストの次のノードを指すように
2つのポインター
l1とl2
を設定します。
最初に仮想ヘッドノードフェイカーに従事します。
上記のフェイカーヘッドノードをラストノードに設定します。
次に、l1とl2を比較します。
小さい方のノードをヘッドノードとして使用します。
対応するポインタを小さい方のノードに戻します。
それらが等しい場合は、最初に2つの等しいノードを配置し、両方のポインタを戻します。
最後に、ポインターがNoneを指す場合、lastnodeの次を別のポインターにポイント
し、ヘッドノードに戻ります。
# 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:
faker = ListNode(0)
lastnode = faker
while l1 is not None and l2 is not None:#l1和l2都不是各自链表的末尾
if l1.val == l2.val:
lastnode.next = ListNode(l1.val)
lastnode.next.next = ListNode(l2.val)
lastnode = lastnode.next.next
l1 = l1.next
l2 = l2.next
elif l1.val < l2.val:#l1小,先录入l1
lastnode.next = ListNode(l1.val)
lastnode = lastnode.next
l1 = l1.next
elif l2.val < l1.val:
lastnode.next = ListNode(l2.val)
lastnode = lastnode.next
l2 = l2.next
if l1 is None and l2 is not None:
lastnode.next = l2
elif l2 is None and l1 is not None:
lastnode.next = l1
return faker.next