关闭

【Java】汉诺塔问题

218人阅读 评论(0) 收藏 举报
import java.util.Stack;


public class Tower {
	private Stack<Integer> disks;
	private int index;
	public Tower(int i) {
		disks = new Stack<Integer>();
		index = i;
	}
	
	public int index() {
		return index;
	}
	
	public void add(int d) {
		if (! disks.isEmpty() && disks.peek() <= d) {
			System.out.println("Error place in disk" + d);
		}
		else {
			disks.push(d);
		}
	}
	
	public void moveTopTo(Tower t) {
		int top = disks.pop();
		t.add(top);
		System.out.println("Move disk " + top + " from " + index() + " to "+ t.index());
	}
	
	public void moveDisks(int n, Tower destination, Tower buffer) {
		if (n > 0) {
			moveDisks(n-1, buffer, destination);
			moveTopTo(destination);
			buffer.moveDisks(n - 1, destination, this);
		}
	}
}

public static void main(String[] args) {
	int n = 3;
	Tower[] towers = new Tower[n];
	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]);
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:109960次
    • 积分:2996
    • 等级:
    • 排名:第11735名
    • 原创:180篇
    • 转载:107篇
    • 译文:0篇
    • 评论:10条
    文章分类
    最新评论