Skip to content

Instantly share code, notes, and snippets.

@tonycox
Created March 21, 2017 16:17
Show Gist options
  • Save tonycox/5dc9730bbff140bf7e6ce49f781f880a to your computer and use it in GitHub Desktop.
Save tonycox/5dc9730bbff140bf7e6ce49f781f880a to your computer and use it in GitHub Desktop.
Merging two sorted lists into first one
static void merge(List<Long> first, List<Long> second) {
ListIterator<Long> firstIter = first.listIterator();
ListIterator<Long> secondIter = second.listIterator();
Long a = getNext(firstIter);
Long b = getNext(secondIter);
while (a != null && b != null) {
if (a > b) {
firstIter.previous();
firstIter.add(b);
firstIter.next();
b = getNext(secondIter);
} else {
a = getNext(firstIter);
}
}
while (b != null) {
firstIter.add(b);
b = getNext(secondIter);
}
}
@Nullable
private static Long getNext(ListIterator<Long> iter) {
return iter.hasNext() ? iter.next() : null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment