Created
March 21, 2017 16:17
-
-
Save tonycox/5dc9730bbff140bf7e6ce49f781f880a to your computer and use it in GitHub Desktop.
Merging two sorted lists into first one
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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