package Myfirstjava; import java.util.Stack; public class Test { public static void main(String[] args){ Test hnt = new Test(6); } public Test(int count){ this.count = count; } private void hanNuoTa(int n,char start,char transit,char destination,int level){ if(n == 1){ move(n,start,destination); return; } level++; hanNuoTa(n-1,start,destination,transit,level); move(n,start,destination); hanNuoTa(n-1,transit,start,destination,level); } private class Element{ public int n,level; public char start,transit,destination; public Element(int n,char start,char transit,char destination,int level){ this.n = n; this.start = start; this.transit = transit; this.destination = destination; this.level = level; } } private void hanNuoTa_stack(int n,char start,char transit,char destination,int level){ Stack<Element> stack = new Stack(); stack.push(new Element(n,start,transit,destination,level)); while(!stack.empty()){ Element e = stack.pop(); if(e.n == 1){ move(e.start,e.destination); }else{ stack.push(new Element(n-1,e.transit,e.start,e.destination,level)); move(e.start,e.destination); stack.push(new Element(n-1,e.start,e.destination,e.transit,level)); } e = null; } } /** * 显示效果: * move 1 from A to B * move 2 from A to C * @param mark 节点的标识或名称 * @param start 移动的起点标识或名称 * @param destination 移动的终点标识或名称 */ private void move(int mark,char start,char destination){ StringBuffer sb = new StringBuffer(); sb.append("move "); sb.append(mark); sb.append(" from "); sb.append(start); sb.append(" to "); sb.append(destination); sb.append("/r/n"); System.out.print(sb.toString()); sb.delete(0,sb.length()); } private void move(char start,char destination){ StringBuffer sb = new StringBuffer(); sb.append("move "); sb.append("the top disk from "); sb.append(start); sb.append(" to "); sb.append(destination); sb.append("/r/n"); System.out.print(sb.toString()); sb.delete(0,sb.length()); } private int count;//初始规模 }