zoukankan      html  css  js  c++  java
  • 【递归】汉诺塔的递归与非递归(压栈)

    递归方法很多很多了;

    c语言汉诺塔hanoi问题非递归方法--压栈:

    #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?
    ");
        
        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
    ", a, c);
        else
        {
            hanoi(n - 1, a, c, b);
            printf("%c --> %c
    ", 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;
    
        top++;
        sta[top].n = n; 
        sta[top].x = fr; 
        sta[top].y = to; 
        sta[top].z = by;
    
        while(top > -1)
        {
            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 = a;
                sta[top].z = c;
                
                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("
    move from %c to %c ", a, c);
            }
        }
    }

    此方法还有一点小问题。

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

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

  • 相关阅读:
    团队展示
    平衡二叉树AVLTree
    红黑树原理
    日本楼市崩盘始末
    池化
    Spring配置多数据源
    关于C语言指针几个容易混淆的概念
    .net core 部署 Docker 所遇到的几个问题
    自定义类加载器也是无法实现加载java.lang.String的
    jquery轻量级数字动画插件jquery.countup.js
  • 原文地址:https://www.cnblogs.com/paprikatree/p/10462710.html
Copyright © 2011-2022 走看看