package stack;
import java.util.Stack;
public class MyStack {
//StackA是源柱,StackB是借助柱,StackC是目的柱
//move()方法表示把n个在A柱上的移动到C柱
private static int move(int n, Stack stackA, Stack stackB, Stack stackC) {
if (n == 1) {
stackC.push(stackA.pop());
} else {
//1.先把n-1个从A柱移动到B柱
move(n - 1, stackA, stackC, stackB);
//2.再把A柱上剩下的一个移动到C
stackC.push(stackA.pop());
//3.最后把B柱上的n-1个移动到C柱
move(n - 1, stackB, stackA, stackC);
}
//统计一共移动了几次,源柱上有几个就会移动(2的n次方-1)次
return (1 << n) - 1;
}
public static void main(String[] args) {
Stack<Integer> stackA = new Stack<Integer>();
Stack<Integer> stackB = new Stack<Integer>();
Stack<Integer> stackC = new Stack<Integer>();
for (int i = 1; i <= 5; i++) {
stackA.push(i);
}
System.out.println(stackA.isEmpty());
System.out.println(stackB.isEmpty());
System.out.println(stackC.isEmpty());
for (int i=0;i<stackA.size();i++){
System.out.println(stackA.elementAt(i));
}
System.out.println("=====================");
System.out.println(move(stackA.size(),stackA,stackB,stackC));
System.out.println(stackA.isEmpty());
System.out.println(stackB.isEmpty());
System.out.println(stackC.isEmpty());
System.out.println("=====================");
for (int i=0;i<stackC.size();i++){
System.out.println(stackC.elementAt(i));
}
}
}
利用栈Stack解决汉诺塔问题
最新推荐文章于 2022-06-25 10:06:44 发布