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

• ``````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;
}
}``````

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

• 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;
}
}``````

• Thank you. Very helpfull.

• ``````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;
}
}``````

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