import java.io.*; public class TowersStack{ private static BufferedReader stdin = new BufferedReader( new InputStreamReader( System.in ) ); private static StackX S; public static void TowersOfHanoi(String source, String dest, String temp, int n) { // Initialization: create an activation record with the given // parameters. Set the number of subproblems solved, to zero. // Push the activation record onto the stack ActivationRecord rec = new ActivationRecord(source, dest, temp, n, 0); S.push(rec); while(!S.isEmpty()) { ActivationRecord current = S.pop(); // If one peg needs to be moved: base case if(current.n == 1) System.out.println(current.source+" -> "+current.dest); // recursive case else { // If no subproblem have been solved so far, then // solve the first subproblem if(current.code == 0) { // push the current subproblem back, with code incremented to one current.code++; S.push(current); // Push the first subproblem ActivationRecord newRecord = new ActivationRecord(current.source, current.temp, current.dest, current.n-1, 0); S.push(newRecord); } // If one subproblem has been solved, then solve // the second subproblem else if (current.code == 1) { // push the current subproblem back, with code incremented to one current.code++; S.push(current); // Push the first subproblem ActivationRecord newRecord = new ActivationRecord(current.source, current.dest, current.temp, 1, 0); S.push(newRecord); } // If two subproblems have been solved, then solve the third subproblem else if (current.code == 2) { // push the current subproblem back, with code incremented to two current.code++; S.push(current); // Push the second subproblem ActivationRecord newRecord = new ActivationRecord(current.temp, current.dest, current.source, current.n-1, 0); S.push(newRecord); } } // end of recursive case } // end of main while-loop } public static void main(String[] args) { int n; // Prompt the user System.out.println("Type a positive integer." ); try{ // Read a line of text from the user. String input = stdin.readLine(); // converts a String into an int value n = Integer.parseInt( input ); S = new StackX(n); System.out.println("Type the name of the source peg:"); String source = stdin.readLine(); System.out.println("Type the name of the destination peg:"); String dest = stdin.readLine(); System.out.println("Type the name of the temporary peg:"); String temp = stdin.readLine(); TowersOfHanoi(source, dest, temp, n); } catch(java.io.IOException e) { System.out.println(e); } } // end of main } // end of class