The topic is relatively simple.
My idea is:
set two pointers
l1 and l2
to point to the next node of the two linked lists.
First engage in a virtual head node faker.
Set the above faker head node to lastnode.
Then, compare l1 and l2
Use the smaller one as the head node.
Move the corresponding pointer back to the smaller one.
If they are equal, arrange the two equal nodes first, and move both pointers back.
Finally, when a pointer points to None, point the next of lastnode to another pointer and
return to the head node
# 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