Er,

Merge two ordered lists into a new ordered list and return. A new list is formed by concatenating all the nodes of a given two lists.

The sample

Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4

Train of thought

Create a new pointer to head 3. Iterate over P1 and p2, insert smaller values after head, and move the corresponding Pointers to P1 and p2 by 4. See if p1 and P2 are left

code

function ListNode(val){
    this.val = val
    this.next = null
}

const p1Node1 = new ListNode(1)
const p1Node2 = new ListNode(2)
const p1Node3 = new ListNode(4)

p1Node1.next = p1Node2
p1Node2.next = p1Node3


const p2Node1 = new ListNode(1)
const p2Node2 = new ListNode(3)
const p2Node3 = new ListNode(4)

p2Node1.next = p2Node2
p2Node2.next = p2Node3

function merge(p1, p2) {
    let head = new ListNode()
    let cur = head
    
    while(p1 && p2) {
        if(p1.val <= p2.val) {
            cur.next = p1
            p1 = p1.next
        } else{ cur.next = p2 p2 = p2.next } cur = cur.next } cur.next = p1 ! =null ? p1 : p2
    
    return head.next
}

merge(p1Node1, p2Node1)
Copy the code