Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericntd/ccc0c249de277f514fbcaf5346cc60f5 to your computer and use it in GitHub Desktop.
Save ericntd/ccc0c249de277f514fbcaf5346cc60f5 to your computer and use it in GitHub Desktop.
public static final ListNode<Integer> mergeTwoSortedLists(ListNode<Integer> L1, ListNode<Integer> L2) {
System.out.printf(">>> Merging %s and %s", L1, L2);
System.out.println();
ListNode<Integer> dummyHead = new ListNode<>(new Random().nextInt(), (ListNode<Integer>) null);
ListNode<Integer> current = dummyHead;
ListNode<Integer> p1 = L1;
ListNode<Integer> p2 = L2;
while (p1.getNext() != null && p2.getNext() != null) {
if (p1.getData() <= p2.getData()) {
current.setNext(p1);
p1.getNext();
p1 = p1.getNext();
} else {
current.setNext(p2);
p2 = p2.getNext();
}
current = current.getNext();
}
current.setNext(p1 != null? p1 : p2);
System.out.printf("<<< Merge result : %s", dummyHead.getNext());
System.out.println();
return dummyHead.getNext();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment