</pre><pre name="code" class="java"><pre name="code" class="java">//用栈模拟实现汉诺塔问题
import java.util.*;
public class TestHanNuoTa{
private static int size = 4;
private static Stack A = new Stack(size); //塔A
private static Stack B = new Stack(size); //塔A
private static Stack C = new Stack(size); //塔A
public static void main(String[] args){
for(int i = A.size(); i > 0; i--){ //初始化塔A
A.push(i);
}
print();
System.out.println("-----------------------------------------------");
//开始移动
move(A.size(),A,B,C);
}
public static void move(int size,Stack from,Stack inter,Stack to){
if(size == 1){
to.push(from.pop());
print();
}else{
move(size - 1,from,to,inter);
to.push(from.pop());
print();
move(size - 1,inter,from,to);
}
}
public static void print(){
System.out.println("A: " + A + " B: " + B + " C: " + C);
}
}
class Stack{
int[] array;
int maxLength;
int top;
public Stack(int size){
array = new int[size];
maxLength = size;
top = 0;
}
public void push(int a){
array[top++] = a;
}
public int pop(){
int temp = array[--top];
array[top] = 0;
return temp;
}
public boolean isEmpty(){
return top == 0;
}
public int peek(){
return array[top - 1];
}
public int size(){
return maxLength;
}
public String toString(){
return Arrays.toString(array);
}
}
结果为:
<img src="https://img-blog.csdn.net/20141101103913200?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdGhpbmtfcHJvZ3JhbQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />