链表-合并成有序链表

130 阅读1分钟

真题

真题描述:将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有结点组成的。

示例

输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4

思路

1.原链表本来就是有序的 2.新创建一个头指针head 3.遍历p1和p2,将较小的值插到head后面,对应的p1和p2的指针后移动 4.判断p1和p2还有没有剩余

代码

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)