习题3.10 汉诺塔的非递归实现 (25分)

借助堆栈以非递归(循环)方式求解汉诺塔的问题(n, a, b, c),即将N个盘子从起始柱(标记为“a”)通过借助柱(标记为“b”)移动到目标柱(标记为“c”),并保证每个移动符合汉诺塔问题的要求。

输入格式:

输入为一个正整数N,即起始柱上的盘数。

输出格式:

每个操作(移动)占一行,按柱1 -> 柱2的格式输出。

输入样例:

3

输出样例:

a -> c
a -> b
c -> b
a -> c
b -> a
b -> c
a -> c

理解一下首先我写了下递归的情况,这里讲下思路:

其实最终移盘子可以看做是:

1.将0到n-1个盘子借助c从a移到b;

2.将第n个盘子借助b从a移动到c;

3.最后把0到n-1个盘子借助a移动到c;

#include <stdio.h>

#include <stdlib.h>


void move(char A, char C)

{

printf("%c -> %c\n",A,C);

}

void hanoi(int n, char A, char B, char C);


int main()

{

int n;

scanf("%d",&n);

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

hanoi(n,A,B,C);

return 0;

}



void hanoi( int n, char A, char B, char C )

{

if(n == 1)

{

move(A,C);

}

else

{

hanoi(n-1,A,C,B);

move(A,C);

hanoi(n-1,B,A,C);

}

}

这个憨批题目也不会检测你递归是错的,难点在非递归,这里得用堆栈的思想;

借用一下图https://blog.csdn.net/royzdr/article/details/79032032 出处是这里;

#include <stdio.h>

#include <stdlib.h>

#include <stdbool.h>

#define STACKSIZE 100


typedef struct{

char a;

char b;

char c;

int n;

}ElementType;


typedef struct node *PtrToSnode;

struct node{

ElementType *data;

int top;

int maxsize;

};


typedef PtrToSnode mystack;


mystack creatstack(int maxsize)

{

mystack ms = (mystack)malloc(sizeof(struct node));

ms->data = (ElementType *)malloc(maxsize * sizeof(ElementType));

ms->top = -1;

ms->maxsize = maxsize;

return ms;

}


void pushdata( mystack ms, ElementType x )

{

if( ms->top == ms->maxsize - 1)

{

printf("Stack is Full!\n");

}

else

{

ms->data[++(ms->top)] = x;

}

}


ElementType popdata( mystack ms )

{

if(ms->top == -1)

{

printf("Stack is Empty!\n");

}

else

{

return ms->data[ms->top--];

}

}




void hanoi( int n )

{

mystack ms = creatstack(STACKSIZE);

ElementType tmp,topush;

tmp.a = 'a';

tmp.b = 'b';

tmp.c = 'c';

tmp.n = n;

pushdata(ms, tmp);

while(ms->top != -1)

{

tmp = popdata(ms);

if(tmp.n == 1)

{

printf("%c -> %c\n",tmp.a,tmp.c);

}

else

{

topush.a = tmp.b;

topush.b = tmp.a;

topush.c = tmp.c;

topush.n = tmp.n - 1;

pushdata(ms, topush);

topush.a = tmp.a;

topush.b = tmp.b;

topush.c = tmp.c;

topush.n = 1;

pushdata(ms, topush);

topush.a = tmp.a;

topush.b = tmp.c;

topush.c = tmp.b;

topush.n = tmp.n-1;

pushdata(ms, topush);

}


}

}



int main()

{

int n;

scanf("%d",&n);

hanoi(n);

return 0;

}


这里用到了结构体,堆栈以及结构数组,这里有一个点容易遗忘,当用malloc为指针类型变量申请空间的时候,格式是(ElementType *)malloc(n * sizeof(ElementType));这里的ElementType是你申请的变量的名称,本题这里是一个结构体数组,所以申请的是一个指向结构体的指针的空间,data数组存储的是一堆指针,其余的都是小操作,花了很多时间这道题,做了两次以后还得好好温习!!!

奥力给!

奥力给!

奥力给!

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值