Niuke Top101 JS merges two sorted lists

describe

Input two increasing linked lists, the length of a single linked list is n, merge the two linked lists and make the nodes in the new linked list still be sorted incrementally.

Data range: 0 ≤ n ≤ 1000, -1000 ≤ node value ≤ 1000
Requirements: space complexity O(1), time complexity O(n)

For example, when {1,3,5}, {2,4,6} are input, the merged linked list is {1,2,3,4,5,6}, so the corresponding output is {1,2,3, 4,5,6}, the conversion process is shown in the figure below:

                        

 Or input {-1,2,4}, {1,3,4}, the merged linked list is {-1,1,2,3,4,4}, so the corresponding output is {-1,1 ,2,3,4,4}, the conversion process is shown in the figure below:

                   

 

Example 1

enter:

{1,3,5},{2,4,6}

return value:

{1,2,3,4,5,6}

Example 2

enter:

{},{}

return value:

{}

Example 3

enter:

{-1,2,4},{1,3,4}

return value:

{-1,1,2,3,4,4}

Main ideas:

First of all, you need to judge whether one of the two linked lists is empty, and if it is empty, just return the other linked list directly (for nothing). Then initialize the header, if the first value of the first linked list is less than or equal to the first value of the second linked list, the header is initialized to the first value of the first linked list, and if it is greater than that, it is initialized to the second linked list The first value of , the next key point: Be sure to save the position of the initial pointer of the meter header for later return! ! !

The next step is to perform a merge operation. The condition of the loop is that if one of the first linked list or the second linked list reaches the end of the linked list, it will stop, and then the merge operation is consistent with the idea of ​​​​merge sorting, so I won’t say much here Alright, friends who don’t understand go down and review it by yourself~. The complete code is as follows:

/*function ListNode(x){
    this.val = x;
    this.next = null;
}*/
function Merge(pHead1, pHead2)
{
    // write code here
    let p1,p2=null;
    let pnew=null;
    p1=pHead1;
    p2=pHead2;
    // 判断:如果有一个已经为空了就返回另外一个
    if(p1===null) {
        return p2;
    }
    if(p2===null)
     {
        return p1;
    }
    if(p1.val<=p2.val) {
        pnew=p1;
        p1=p1.next;
    }
    else {
         pnew=p2;
         p2=p2.next;
    } 
    let res=pnew;   
    while(p1!==null&&p2!==null) {
    if(p1.val<=p2.val) {
        pnew.next=p1;
        p1=p1.next;
    }
    else {
        pnew.next=p2;
        p2=p2.next;
    }
        pnew=pnew.next;
    }
    if(p1===null) {
        pnew.next=p2;
    }
    if(p2===null) {
        pnew.next=p1;
    }
    return res;
}

module.exports = {
    Merge : Merge
};

Guess you like

Origin blog.csdn.net/qq_43781887/article/details/128182302