Topic Portal: Portal (click here)
- The general idea of it, two ListNode compare the size of the value, and then have the small one, the rest of the traverse turn back
- Until a ListNode is empty, it is added directly to a linked list of all of the two outer content
- To do so, the time complexity and space complexity are m + n
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode res = new ListNode(-1);
ListNode temp = res;
while (l1 != null && l2 != null) {
ListNode node;
if (l1.val > l2.val) {
node = new ListNode(l2.val);
l2 = l2.next;
} else {
node = new ListNode(l1.val);
l1 = l1.next;
}
temp.next = node;
temp = temp.next;
}
ListNode listNode = l1 == null ? l2 : l1;
while (listNode != null) {
temp.next = new ListNode(listNode.val);
temp = temp.next;
listNode = listNode.next;
}
return res.next;
}
}