Chinaunix首页 | 论坛 | 博客
  • 博客访问: 427112
  • 博文数量: 71
  • 博客积分: 26
  • 博客等级: 民兵
  • 技术积分: 1246
  • 用 户 组: 普通用户
  • 注册时间: 2012-07-23 14:46
个人简介

linux --- 一切皆文件

文章分类

全部博文(71)

文章存档

2021年(1)

2019年(2)

2018年(4)

2017年(7)

2016年(11)

2015年(1)

2014年(2)

2013年(33)

2012年(10)

分类: C/C++

2013-05-20 23:10:55

汉诺塔(递归+栈存储打印)

#include

#define MAXLEN 32
struct _hanno {
    int stack[MAXLEN];
    int index;
}hanno[3];

void hanno_print()
{
    int i,j;
    for(i = 0;i < 3;i ++){
        for(j = 0;j < hanno[i].index;j ++){
            printf("%d ",hanno[i].stack[j]);
        }
        printf("- \n");
    }
}

void hanno_init(int count)
{
    int i;
    for(i = 0;i < count;i ++)
        hanno[0].stack[i] = count - i;
    hanno[0].index = count;
}

/*
    把刚才弹出的盘子压栈到新的柱子上
*/
void push(int dest,int num)
{
    hanno[dest].stack[hanno[dest].index] = num;
    hanno[dest].index ++;
}

/*
    把对应柱子上的盘子弹出
*/
int pop(int src)
{
    hanno[src].index --;
    return hanno[src].stack[hanno[src].index];
}

/*
    移动
*/
void move(int src,int dest)
{
    push(dest,pop(src));
    hanno_print();
}

/*
    递归计算
*/
void myhanno(int src,int dest,int tmp,int count)
{
    if(count == 1){    
        move(src,dest);
        return ;
    }

    myhanno(src,tmp,dest,count - 1);
    move(src,dest);
    myhanno(tmp,dest,src,count - 1);
}

int main(int argc,char **argv)
{
    int count;
    if(argc == 1){
        printf("please enter a argue\n");
    return -1;
    }
    count = atoi(argv[1]);
    if(count > 32){
        printf("over the max num \n max num is 32\n");
        return -1;
    }

    hanno_init(count);
    hanno_print();
    myhanno(0,2,1,count);
    
    return 0;
}





阅读(1421) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~