Description:
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Solution:
Remember the very important step in the merge sort? About merging two arrays. This one is almost the same, every time we get the smaller one of the remaining tow head.
Be careful when at least one of the lists is empty.
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head;
if (l1 == null)
return l2;
if (l2 == null)
return l1;
if (l1.val < l2.val) {
head = l1;
l1 = l1.next;
head.next = null;
} else {
head = l2;
l2 = l2.next;
head.next = null;
}
ListNode tot = head, next;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
next = l1;
l1 = l1.next;
next.next = null;
} else {
next = l2;
l2 = l2.next;
next.next = null;
}
tot.next = next;
tot = tot.next;
}
if (l1 != null)
tot.next = l1;
if (l2 != null)
tot.next = l2;
return head;
}
}