# 问题描述

1. 用栈模拟汉诺塔问题

(1) 每次只能移动一个盘子。
(2) 每个盘子从堆的顶部被移动后，只能置放于下一个堆中。
(3) 每个盘子只能放在比它大的盘子上面。

towers[0]: []
towers[1]: []
towers[2]: [2,1,0]

towers[0]: []
towers[1]: []
towers[2]: [9,8,7,6,5,4,3,2,1,0]

# 代码实现——lintcode227题

public class Tower {
private Stack<Integer> disks;
/*
* @param i: An integer from 0 to 2
*/
public Tower(int i) {
// create three towers
this.disks = new Stack<>();
}

/*
* @param d: An integer
* @return: nothing
*/
public void add(int d) {
// Add a disk into this tower
if (!disks.isEmpty() && disks.peek() <= d) {
System.out.println("Error placing disk " + d);
} else {
disks.push(d);
}
}

/*
* @param t: a tower
* @return: nothing
*/
public void moveTopTo(Tower t) {
// Move the top disk of this tower to the top of t.
Integer a = this.disks.pop();
t.disks.push(a);
}

/*
* @param n: An integer
* @param destination: a tower
* @param buffer: a tower
* @return: nothing
*/
public void moveDisks(int n, Tower destination, Tower buffer) {
// Move n Disks from this tower to destination by buffer tower
if(n==1){
this.moveTopTo(destination);
}else{
this.moveDisks(n-1,buffer,destination);
this.moveTopTo(destination);
// Tower t = new Tower(0);
// t = this;
buffer.moveDisks(n-1,destination,this);
}

}

/*
* @return: Disks
*/
public Stack<Integer> getDisks() {
// write your code here
//System.out.println("hahah");
return disks;
}
}

/**
* Your Tower object will be instantiated and called as such:
* Tower[] towers = new Tower[3];
* for (int i = 0; i < 3; i++) towers[i] = new Tower(i);
* for (int i = n - 1; i >= 0; i--) towers[0].add(i);
* towers[0].moveDisks(n, towers[2], towers[1]);
* print towers[0], towers[1], towers[2]
*/

• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 打赏

打赏

小驰驰呕吼**

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 举报
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文

03-31
05-10
03-25
04-19
05-23
04-29
07-13
12-18
03-25
09-04
12-24
09-09
©️2020 CSDN 皮肤主题: 创作都市 设计师:CSDN官方博客