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;
}
}
How can I make this solution shorter? Please, give some advise. Java(247ms)


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 loopspublic 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; } }