-
-
Save tamboer/3aed96e0ba32ae816f782e4f4763c658 to your computer and use it in GitHub Desktop.
Reverse a List in Java
This file contains hidden or 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
/** | |
* Reverses a given List | |
* using Collections.reverse() method | |
* @param list | |
* @author Jon Bonso | |
*/ | |
public static void reverse(List<?> list) { | |
Collections.reverse(list); | |
} | |
/** | |
* Reverses a given List manually by using ListIterator | |
* @author Jon Bonso | |
* @param list | |
*/ | |
public static void reverseV2(List<?> list) { | |
ListIterator reverseIterator = list.listIterator(list.size()); | |
ListIterator forwardIterator = list.listIterator(); | |
int ctr = 0; | |
while (ctr < (list.size()/2) ){ | |
Object temp = forwardIterator.next(); | |
forwardIterator.set(reverseIterator.previous()); | |
reverseIterator.set(temp); | |
ctr++; | |
} | |
} | |
public static void main(String... args) { | |
List<String> studentsList = new LinkedList<String>(); | |
for (int i=0; i<10; i++) { | |
studentsList.add( i + " Student"); | |
} | |
System.out.println(studentsList); | |
// reverse(studentsList); | |
reverseV2(studentsList); | |
System.out.println(studentsList); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment