/* */ /* File: /home/cs1/Java/HanoiIteratively.java */ /* Author: Stephen Gilmore */ /* Date: 1st February 2000 */ /* Copyright: School of Computer Science, The University of Edinburgh */ /* */ import java.util.Stack; class HanoiIteratively { static class Move { int n; char src; char dst; Move (int n, char src, char dst) { this.n = n; this.src = src; this.dst = dst; } } static void hanoi(int n, char src, char dst) { Stack s = new Stack(); s.push (new Move(n, src, dst)); while (!s.empty()) { Move m = (Move) s.pop(); if (m.n == 1) System.out.println ("Move disk from " + m.src + " to " + m.dst); else { char spare = (char) (('A' + 'B' + 'C') - (m.src + m.dst)); // Add last move to do first on stack s.push(new Move(m.n - 1, spare, m.dst)); s.push(new Move(1, m.src, m.dst)); s.push(new Move(m.n - 1, m.src, spare)); } } } public static void main (String[] args) { int n = Integer.parseInt(args[0]); hanoi(n, 'A', 'B'); } }