requirements

Merges two ascending lists into a new ascending list and returns. A new list is formed by concatenating all the nodes of a given two lists.

Example 1:

Input: l1 = [1,2,4], l2 = [1,3,4]Copy the code

Example 2:

Input: L1 = [], L2 = [] output: []Copy the code

Example 3:

Input: L1 = [], L2 = [0] output: [0]Copy the code

Tip:

  • The number of nodes in two linked lists ranges from 0 to 50.
  • -100 <= Node.val <= 100
  • Both L1 and L2 are arranged in non-decreasing order

The core code

class ListNode:
    def __init__(self, val=0.next=None) :
        self.val = val
        self.next = next
        
class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        newhead = ListNode(0)
        p = newhead
        while l1 and l2:
            if l1.val < l2.val:
                p.next = ListNode(l1.val)
                l1 = l1.next
            else:
                p.next = ListNode(l2.val)
                l2 = l2.next
            p = p.next
        if l1:
            p.next = l1
        else:
            p.next = l2
        return newhead.next
Copy the code

Focus on the topic

Answer:

We first create a node to store the new list, then iterate through L1 and L2, adding smaller values to the new list, and then at the end of the loop, attach the remaining lists to the end of the new list.