My 15ms Java solution based on merge sort


  • 2
    public class Solution {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            ListNode l3 =new ListNode(0);
            ListNode head = l3;
            while(l1!=null&&l2!=null){
                if(l1.val<l2.val){
                    l3.next = l1;
                    l3 = l3.next;
                    l1 = l1.next;
                }else{
                    l3.next = l2;
                    l3 = l3.next;
                    l2 = l2.next;
                }
            }
            while(l1!=null){
                l3.next = l1;
                l3 = l3.next;
                l1 = l1.next;
            }
            while(l2!=null){
                l3.next = l2;
                l3 = l3.next;
                l2 = l2.next;
            }
            return head.next;
        }
    }
    

  • 0
    Y

    You don't need the two while loops at the end, it can be substituted as two if statements to make the code cleaner.


  • 0

    Hi, do you mean I could remove the two loop at end? Originally, I think these 2 loops could check if there are any nodes left in linkedlist respectively. Does it work if you remove the last 2 loops?


Log in to reply
 

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