首页 > 其他 > 详细

【递归】汉诺塔的递归与非递归(压栈)

时间:2019-03-02 20:37:53      阅读:276      评论:0      收藏:0      [点我收藏+]

递归很多了;

c语言的非递归方法:

#include <stdio.h>

struct stack
{
    int n;
    char x, y, z;
}sta[200];



void hanoi(int n, char a, char b, char c);
void hanoiStack(int n, char fr, char to, char by);

int main(void)
{
    int n;
    printf("How many hanoi TOWERS?\n");
    
    for(int loop = 0; loop < 200; loop++)
    {
        sta[loop].n = 0;
        sta[loop].x = 0;
        sta[loop].y = 0;
        sta[loop].z = 0;
    }
    
    scanf("%d", &n);
    hanoiStack(n, a, b, c);
    return 0;
}
void hanoi(int n, char a, char b, char c)
{
    if(n == 1)
        printf("%c --> %c\n", a, c);
    else
    {
        hanoi(n - 1, a, c, b);
        printf("%c --> %c\n", a, c);
        hanoi(n - 1, b, a, c);
    }
}
void hanoiStack(int n, char fr, char to, char by)
{
    int top = 1, n1, a, b, c;

    sta[top].n = n; 
    sta[top].x = fr; 
    sta[top].y = by; 
    sta[top].z = to;

    while(top > 0)
    {
        n1 = sta[top].n;
        a = sta[top].x;
        b = sta[top].y;
        c = sta[top].z;
        top--;
        
        // 下面压栈
        if(n1 > 1)
        {
            top++;
            sta[top].n = n1 - 1;
            sta[top].x = b;
            sta[top].y = c;
            sta[top].z = a;
            
            top++;
            sta[top].n = 1;
            sta[top].x = a;
            sta[top].z = c;
            
            top++;
            sta[top].n = n1 - 1;
            sta[top].x = a;
            sta[top].y = c;
            sta[top].z = b;

        }
        else
        {
            printf("\nmove from %c to %c ", a, c);
        }
    }
}

此方法还有一点小问题。

过程类似于:https://blog.csdn.net/weixin_37817685/article/details/78649373

解说2:https://wenku.baidu.com/view/a899321253d380eb6294dd88d0d233d4b14e3fa2.html

【递归】汉诺塔的递归与非递归(压栈)

原文:https://www.cnblogs.com/paprikatree/p/10462710.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!