Posted By

djangofan on 12/13/12


Tagged

java linked-list


Versions (?)

Java - reverse a linked list


 / Published in: Java
 

Reverse a linked list using Java.

  1. import java.util.ArrayList;
  2. import java.util.Iterator;
  3. import java.util.List;
  4.  
  5. public class Recur {
  6.  
  7. private static List<String> list = new ArrayList<String>();
  8. private static List<String> reversedList = new ArrayList<String>();
  9.  
  10. public static void main( String[] args ) {
  11. list.add("one");
  12. list.add("two");
  13. list.add("three");
  14. list.add("four");
  15.  
  16. reverseList( list );
  17.  
  18. printList( reversedList );
  19. }
  20.  
  21. public static void reverseList( List<String> listarg ) {
  22. String firstitem = null;
  23. if ( listarg.size() == 0 ) {
  24. return;
  25. } else {
  26. firstitem = listarg.get(0);
  27. listarg.remove(0);
  28. }
  29. reverseList( listarg );
  30. reversedList.add( firstitem );
  31. }
  32.  
  33. public static void printList( List<String> listarg ) {
  34. Iterator<String> listIterator = listarg.iterator();
  35. while( listIterator.hasNext() ) {
  36. String item = listIterator.next();
  37. System.out.println( item );
  38. }
  39. }
  40. }

Report this snippet  

You need to login to post a comment.