合并两个排序的链表

2019-11-11  本文已影响0人  ElricTang

《剑指offer》刷题笔记。如有更好解法,欢迎留言。

关键字:链表

题目描述:

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

思路:

/*function ListNode(x){
    this.val = x;
    this.next = null;
}*/
function Merge(pHead1, pHead2)
{
    let newList = new ListNode(-1);
    let cur = newList;
    while(pHead1 !== null && pHead2 !== null){
        if(pHead1.val < pHead2.val){
            cur.next = pHead1;
            pHead1 = pHead1.next;
        }else{
            cur.next = pHead2;
            pHead2 = pHead2.next;
        }
        cur = cur.next;
    }
    if(pHead1 !== null) cur.next = pHead1;
    if(pHead2 !== null) cur.next = pHead2;
    return newList.next;
}
上一篇 下一篇

猜你喜欢

热点阅读