汉诺塔实现c与java

 老师让用java实现汉诺塔,网上搜索了一篇C的实现,与大家共享:

下面是java

import java.io.*;
public class HanNuoTa{

  public static void main(String[] args) throws IOException{

    System.out.println("请输入你要移的盘的总数:");

    int n =(int) System.in.read();

    char a = 'A', b = 'B', c = 'C';

    hanio(n, a, b, c);

  }

  public static void hanio(int n, char a, char b, char c) {

    if (n == 1) {  //如果只有一个盘子则直接把盘子从a 移到b

      System.out.println("move " + a + " to " + b);

    }

    else { //超过一个盘子的情况

      hanio( (byte) (n - 1), a, c, b); //将a杆上n-1个盘子借助于b先移到c杆

      System.out.println("move " + a + " to " + b); //将a杆上第n个盘子从a移到b杆

      hanio( (byte) (n - 1), c, b, a); //将c杆上n-1个盘子借助a移到b杆

    }

  }

}

 

下面是C:

void he(char x,char y)
{ printf("%c---->%c/n",x,y);
}
void she(int n,char first,char second,char third)
{
if(n==1)he(first,third);
 else
 {she(n-1,first,third,second);
 he(first,third);
 she(n-1,second,first,third);
 }
}
main()
{
int x;
printf("input the number of diskes:");
scanf("%d",&x);
printf("the step to moving %3d diskes:/n",x);
she(x,'A','B','C');
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值