Also note: I'm unable to call the reverse() method from the Collections class.
Expand|Select|Wrap|Line Numbers
- import java.util.*;
- import java.util.ListIterator;
- import java.io.*;
- public class ReverseList
- {
- public static void main (String[] args)
- {
- LinkedList<String> phrase = new LinkedList<String>();
- phrase.add("Four");
- phrase.add("score");
- phrase.add("and");
- phrase.add("seven");
- phrase.add("years");
- phrase.add("ago");
- System.out.println("Phrase in normal order: " + phrase);
- reverse(phrase);
- System.out.println("Phrase in reverse order: " + phrase);
- }
- public static LinkedList<String> reverse(LinkedList<String> a)
- {
- ListIterator<String> order = a.listIterator(a.size());
- LinkedList<String> reversed = new LinkedList<String>();
- while(order.hasPrevious())
- {
- reversed.add(order.previous());
- }
- return reversed;
- }