Hello,
I try to avoid modification of original lists passed in - by copying the data from the link node
The original Java solution:
public static ListNode<Integer> mergeTwoSortedLists(ListNode<Integer> L1,
ListNode<Integer> L2) {
// Creates a placeholder for the result.
ListNode<Integer> dummyHead = new ListNode<>(0, null);
ListNode<Integer> current = dummyHead;
ListNode<Integer> p1 = L1, p2 = L2;
while (p1 != null && p2 != null) {
if (p1.data <= p2.data) {
current.next = p1;
p1 = p1.next;
} else {
current.next = p2;
p2 = p2.next;
}
current = current.next;
}
// Appends the remaining nodes of p1 or p2.
current.next = p1 != null ? p1 : p2;
return dummyHead.next;
}
My solution to avoid modification:
public static ListNode<Integer> mergeTwoSortedListsWithoutModifyingOriginal(ListNode<Integer> L1,
ListNode<Integer> L2) {
// Creates a placeholder for the result.
ListNode<Integer> dummyHead = new ListNode<>(0, null);
ListNode<Integer> current = dummyHead;
ListNode<Integer> p1 = L1, p2 = L2;
while (p1 != null && p2 != null) {
if (p1.data <= p2.data) {
current.next = new ListNode(p1.data, null);
p1 = p1.next;
} else {
current.next = new ListNode(p2.data, null);
p2 = p2.next;
}
current = current.next;
}
// Appends the remaining nodes of p1 or p2.
current.next = p1 != null ? new ListNode(p1.data, p1.next) : p2 != null ? new ListNode(p2.data, p2.next) : null;
return dummyHead.next;
}