Merge L2 into L1


  • 0
    C

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    if(l1 == null) return l2;
    if(l2 == null) return l1;
    ListNode cur1 = l1, prev1 = null;
    ListNode cur2 = l2;
    while(cur1 != null && cur2 != null){
    while(cur1 != null && cur2!=null && cur1.val <= cur2.val){
    prev1 = cur1;//不断更新prev1使得prev1指向满足条件的最后一个节点
    cur1 = cur1.next;
    }
    if(cur1 == null){//将cur2插入到L1队尾
    prev1.next = cur2;
    break;
    }
    else if(cur1 == l1){//将cur2插入L1队首
    ListNode myFirstNode = new ListNode(cur2.val);
    myFirstNode.next = l1;
    l1 = myFirstNode;
    prev1 = myFirstNode;
    }
    else{//将cur2插入队列L1中
    ListNode insert = new ListNode(cur2.val);
    ListNode oldNext = prev1.next;
    prev1.next = insert;
    insert.next = oldNext;
    prev1 = insert;
    }
    cur2 = cur2.next;
    }
    return l1;
    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.