1 /*Hanoi Non-recursive implementation--using stack2 * 1. Create a stack in which each element of the stack contains information: Plate number, 3 tower-seat variable3 * 2. Advanced stack, in the use of the loop to determine whether the stack empty,4 * 3. Non-empty case, out of the stack, check whether there is only one plate--move directly, or simulate the case of the previous recursion--not 15 * 4. All movements are completed until the stack is empty and the loop is closed. 6 * */7 classstack11{8towers[] tt =NewTowers[20];9 inttop =-1;Ten One Public BooleanIsEmpty () { A returntop = =-1; - } - the Public voidpush (Towers t) { -Tt[++top] =T; - } - + PublicTowers Pop () { - returntt[top--]; + } A } at - classtowers{ - intDiskN; - Charfrom ; - CharInter; - Charto ; in PublicTowers (intDISKN,CharFromCharInterCharTo ) { - This. DiskN =DiskN; to This. from =from ; + This. Inter =Inter; - This. to =to ; the } * $ }Panax Notoginseng - Public classHannotower_stack { the + Public Static voidMain (string[] args) { ATowers T1 =NewTowers (3, ' A ', ' B ', ' C '); the dotowers (t1); + } - $ Private Static voiddotowers (Towers t1) { $STACK11 stack =NewStack11 (); - Stack.push (t1); - while(!Stack.isempty ()) { theTowers temp =Stack.pop (); - //processing is the case of a plate--all print statements are printed from hereWuyi if(Temp.diskn = = 1){ theSYSTEM.OUT.PRINTLN ("Top disk" + "from" + Temp.from + "to" +temp.to); - } Wu //Note that the order in which the moves are processed is a-c-b,a-b-c,b-a-c. So the order of the stacks is reversed. - Else{ AboutStack.push (NewTowers (temp.diskn-1, temp.inter,temp.from,temp.to)); $Stack.push (NewTowers (1, temp.from,temp.inter,temp.to)); -Stack.push (NewTowers (temp.diskn-1, Temp.from,temp.to,temp.inter)); - } - } A + } the -}
Execution Result:
Top disk from A to C
Top disk from A to B
Top disk from C to B
Top disk from A to C
Top disk from B to A
Top disk from B to C
Top disk from A to C
Data structure--Hanoi--implementation of non-recursive---Java with stack