import java.util.Iterator; import java.util.LinkedList; import java.util.Random; import javax.swing.JOptionPane; /* * LinkedListRecursionExerciseSolution.java * * Created on October 2, 2005, 3:55 PM * */ /** * * @author Bill Kraynek */ public class LinkedListRecursionExerciseSolution { class Node { Object data; Node next; Node() {} Node(Object data, Node next) { this.data = data; this.next = next; } } // end Node String listToString(Node head) { if( head.next == null ) return ""; return head.next.data + ", " + listToString(head.next); } // end listToString String listReverseToString(Node head) { if( head.next == null ) return ""; return listReverseToString(head.next) + ", " + head.next.data; } // end listToString String linkedListToString(Iterator itr) { if( !itr.hasNext() ) return ""; return itr.next() + ", " + linkedListToString(itr); } // end listToString String linkedListReverseToString(Iterator itr) { if( !itr.hasNext() ) return ""; Object x = itr.next(); return linkedListReverseToString(itr) + ", " + x; } // end listToString /** Creates a new instance of LinkedListRecursionExerciseSolution */ public LinkedListRecursionExerciseSolution() { Random r = new Random(); Node head = new Node(); LinkedList linkedList = new LinkedList(); Node p = head; for( int i = 0; i < 10; i++ ) { Integer x = new Integer(r.nextInt(100)); p.next = new Node(x,p.next); p = p.next; linkedList.add(x); } // end for String out = ""; String list = listToString(head); out += "Node list: { " + list.substring(0,list.length()-2) + " }\n"; list = listReverseToString(head); out += "Node list reversed: { " + list.substring(2) + " }\n"; Iterator listItr = linkedList.iterator(); list = linkedListToString(listItr); out += "LinkedList: { " + list.substring(0,list.length()-2) + " }\n"; listItr = linkedList.iterator(); list = linkedListReverseToString(listItr); out += "LinkedList reversed: { " + list.substring(1) + " }\n"; JOptionPane.showMessageDialog(null,out); } /** * @param args the command line arguments */ public static void main(String[] args) { new LinkedListRecursionExerciseSolution(); } }