[leetcode] Merge two ordered lists [Easy Difficulty]

Question description

Merge the two ascending linked lists into a new ascending linked list and return. The new linked list is formed by concatenating all the nodes of the two given linked lists.

Example

Insert image description here
Input : l1 = [1,2,4], l2 = [1,3,4]
Output : [1,1,2,3,4,4]

Input : l1 = [], l2 = []
Output : []

Input : l1 = [], l2 = [0]
Output : [0]

Sample code

Solution : merge directly

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} list1
 * @param {ListNode} list2
 * @return {ListNode}
 */
var mergeTwoLists = function(list1, list2) {
    
    
    while(list2){
    
    
        list1=mount(new ListNode(list2.val,list2.next),list1);
        list2=list2.next;
    }
    return list1;
};
const mount=(node,list)=>{
    
    
    let rowNode=list;
    let lastNode=list;
    let flag=false;
    node.next=null;//断开之前的 否则会gg
    if(list==null) return node;
    while(list){
    
    
        if(node.val<=list.val){
    
    
            if(lastNode==list){
    
    
                //添加首位置
                let rootNode=node;
                node.next=list;
                rowNode=rootNode;
            }else{
    
    
                //添加在中间
                lastNode.next=node;
                node.next=list;
            }
            flag=true;
           break;
        }else{
    
    
            lastNode=list;
            list=list.next;
        }
    }
    if(!flag){
    
    
        //添加在屁股后
        lastNode.next=node;
    }
     return rowNode;
}

Tip

The method of disassembling, merging, and disassembling again may be clumsy, but it is better in that it is simple to understand.

Supongo que te gusta

Origin blog.csdn.net/qq_33183456/article/details/135444383
Recomendado
Clasificación