227.Mock Hanoi Tower by Stacks

public class Tower {
private Stack<Integer> disks;
// create three towers (i from 0 to 2)
public Tower(int i) {
disks = new Stack<Integer>();
}

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

// @param t a tower
// Move the top disk of this tower to the top of t.
public void moveTopTo(Tower t) {
    // Write your code here
    int temp = disks.pop();
    t.add(temp);
}

// @param n an integer
// @param destination a tower
// @param buffer a tower
// Move n Disks from this tower to destination by buffer tower
public void moveDisks(int n, Tower destination, Tower buffer) {
    // Write your code here
    if (n == 0) return;
    if (n == 1) {
        moveTopTo(destination);
        return;
    }
    moveDisks(n - 1, buffer, destination);
    moveTopTo(destination);
    buffer.moveDisks(n - 1, destination, this);
}

public Stack<Integer> getDisks() {
    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]
*/
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語(yǔ)法,類相關(guān)的語(yǔ)法,內(nèi)部類的語(yǔ)法,繼承相關(guān)的語(yǔ)法,異常的語(yǔ)法,線程的語(yǔ)...
    子非魚_t_閱讀 34,819評(píng)論 18 399
  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,931評(píng)論 0 33
  • 青山深處人家 ,曼妙阿紫香茶 多少月色文墨,琴聲笑語(yǔ),共享裊裊炊煙。
    子興閱讀 351評(píng)論 1 13
  • 創(chuàng)城工作已進(jìn)入最后的關(guān)鍵時(shí)期,渣管科全體團(tuán)結(jié)一心,多措并舉,嚴(yán)厲打擊渣土非法運(yùn)輸,保證城市的整潔面貌,確...
    wuouwuouou閱讀 267評(píng)論 0 0
  • 網(wǎng)絡(luò)服務(wù)流程 DNS Lookup TCP Hankshake TLS Hankshake TCP/HTTP Re...
    李冬冬閱讀 1,260評(píng)論 1 50

友情鏈接更多精彩內(nèi)容