1 /*汉诺塔非递归实现--利用栈 2 * 1.创建一个栈,栈中每个元素包含的信息:盘子编号,3个塔座的变量 3 * 2.先进栈,在利用循环判断是否栈空, 4 * 3.非空情况下,出栈,检查是否只有一个盘子--直接移动,否则就模拟前面递归的情况--非1的情况 5 * 4.直到栈空就结束循环,就完成全部的移动。 6 * */ 7 class Stack11{ 8 Towers[] tt = new Towers[20]; 9 int top = -1; 10 11 public boolean isEmpty(){ 12 return top == -1; 13 } 14 15 public void push(Towers t){ 16 tt[++top] = t; 17 } 18 19 public Towers pop(){ 20 return tt[top--]; 21 } 22 } 23 24 class Towers{ 25 int diskN; 26 char from; 27 char inter; 28 char to; 29 public Towers(int diskN, char from, char inter, char to) { 30 this.diskN = diskN; 31 this.from = from; 32 this.inter = inter; 33 this.to = to; 34 } 35 36 } 37 38 public class HannoTower_Stack { 39 40 public static void main(String[] args) { 41 Towers t1 = new Towers(3,'A','B','C'); 42 doTowers(t1); 43 } 44 45 private static void doTowers(Towers t1) { 46 Stack11 stack = new Stack11(); 47 stack.push(t1); 48 while(!stack.isEmpty()){ 49 Towers temp = stack.pop(); 50 //处理是一个盘子的情况--所有打印语句都从这里打印 51 if(temp.diskN == 1){ 52 System.out.println("Top disk " + "from " + temp.from + " to " + temp.to); 53 } 54 //注意处理移动的顺序本来是A-C-B,A-B-C,B-A-C.所以进栈的顺序相反 55 else{ 56 stack.push(new Towers(temp.diskN-1,temp.inter,temp.from,temp.to)); 57 stack.push(new Towers(1,temp.from,temp.inter,temp.to)); 58 stack.push(new Towers(temp.diskN-1,temp.from,temp.to,temp.inter)); 59 } 60 } 61 62 } 63 64 }
执行结果:
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