1
+ package ch_20 ;
2
+
3
+ import java .util .Scanner ;
4
+ import java .util .Stack ;
5
+
6
+ /**
7
+ * 20.22 (Nonrecursive Tower of Hanoi) Implement the moveDisks method in Listing
8
+ * 18.8 using a stack instead of using recursion.
9
+ */
10
+ public class Exercise20_22 {
11
+
12
+ private static final Stack <HanoiMove > STACK = new java .util .Stack <>();
13
+
14
+ public static void main (String [] args ) {
15
+
16
+ Scanner input = new Scanner (System .in );
17
+ System .out .print ("Enter number of disks: " );
18
+ int n = input .nextInt ();
19
+ System .out .println ("The moves are:" );
20
+ moveDisks (n , 'A' , 'B' , 'C' );
21
+ }
22
+
23
+ public static void moveDisks (int n , char fromTower ,
24
+ char toTower , char auxTower ) {
25
+ STACK .push (new HanoiMove (false , n , fromTower , toTower , auxTower ));
26
+ while (!STACK .isEmpty ()) {
27
+ HanoiMove hanoiMove = STACK .pop ();
28
+ n = hanoiMove .n ;
29
+ fromTower = hanoiMove .fromTower ;
30
+ toTower = hanoiMove .toTower ;
31
+ auxTower = hanoiMove .auxTower ;
32
+ if (hanoiMove .isLastInFromTower )
33
+ System .out .println ("Move disk " + n + " from " +
34
+ hanoiMove .fromTower + " to " + hanoiMove .toTower );
35
+ else {
36
+ if (n == 1 )
37
+ System .out .println ("Move disk " + n + " from " +
38
+ hanoiMove .fromTower + " to " + hanoiMove .toTower );
39
+ else {
40
+ STACK .push (new HanoiMove (false , n - 1 , auxTower , toTower , fromTower ));
41
+ STACK .push (new HanoiMove (true , n , fromTower , toTower , auxTower ));
42
+ STACK .push (new HanoiMove (false , n - 1 , fromTower , auxTower , toTower ));
43
+ }
44
+ }
45
+ }
46
+ }
47
+
48
+ public static class HanoiMove {
49
+ boolean isLastInFromTower = false ;
50
+ int n ;
51
+ char fromTower ;
52
+ char toTower ;
53
+ char auxTower ;
54
+
55
+ HanoiMove (boolean isLastInFromTower , int n , char fromTower , char toTower , char auxTower ) {
56
+ this .isLastInFromTower = isLastInFromTower ;
57
+ this .n = n ;
58
+ this .fromTower = fromTower ;
59
+ this .toTower = toTower ;
60
+ this .auxTower = auxTower ;
61
+ }
62
+ }
63
+ }
0 commit comments