How can I make this solution shorter? Please, give some advise. Java(247ms)


  • 0
    O
    public class Solution {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            ListNode list, result; 
             if (l1 != null) {
                 if (l2 == null) {
                     return l1;
                 }
                 if (l1.val <= l2.val) {
                     list = l1;
                     result = l1;
                     l1 = l1.next;
                 } else {
                     list = l2;
                     result = l2;
                     l2 = l2.next;
                 }
             } else {
                 return l2;
             }
             while (l1 != null && l2 != null) {
             	 if (l1.val <= l2.val) {
             		 list.next = l1;
             		 l1 = l1.next;
             	 } else {
             		 list.next = l2;
             		 l2 = l2.next;
             	 }
             	 list = list.next;
              }
              while (l1 != null) {
         		 list.next = l1;
         		 l1 = l1.next;
             	 list = list.next;
              }
              while (l2 != null) {
         		 list.next = l2;
         		 l2 = l2.next;
             	 list = list.next;
              }
              
              return result;
        }
    }

  • -3
    B

    Please check this question (My C++ solution 12ms)


  • 6
    F

    One while loop is enough to solve this problem.

    because while l1 or l2 equals to null, you can just make your "list.next" equals to the one which is "not null", then all of the rest nodes will be appended.

    here is my code, wish it can help: please focus on the " headcopy.next = (l1 == null ? l2 : l1); this one sentence can reduce your first 3 if conditions and the last 2 while loops

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

  • 0
    O

    Thank you. Very helpfull.


  • 0
    L
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        if (!l1) return l2;
        if (!l2) return l1;
        if (l1->val < l2->val) {
            l1->next = mergeTwoLists(l1->next, l2);
            return l1;
        } else {
            l2->next = mergeTwoLists(l1, l2->next);
            return l2;
        }
    }

Log in to reply
 

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