rain487 2022-01-26 16:12 采纳率: 40%
浏览 46
已结题

堆栈 汉诺塔的非递归实现

img


img


问题应该出在这里了,这样定义有什么不对吗?
跟着网上的代码,写了一部分


#include<stdio.h>
#include<stack>
char s[4]={'0','a','b','c'};
stack<int> a[4];//栈数组 

void move(int now,int next);
int main(){
    int n;
    scanf("%d",&n);
    int i;
    for(i=0;i<n;i++){
        a[1].push(n-i); 
    }
    if(n%2==1){
        s[2]='c';
        s[3]='b';
    }
    while(1){
        int next;
        for(i=1;i<=3;i++){//下一个杆 
            if(!a[i].empty() ){//为空 
                if(a[i].top() ==1){
                    if(i==3)next=1;
                    else next=i+1;
                    move(i,next);
                    break;
                }
            }
            if(a[2]==n||a[3])==n;break;
            int other1,other2;
            switch(next){
                case 1:other1=2,other2=3;break;
                case 2:other1=3,other2=1;break;
                case 3:other1=1,other2=2;break;
            }
            if(a[other1].empty() ){
                move(other2,other1);
            }
            else if(a[other2].empty() ){
                move(other1,other2);
            }
            else{
                if(a[other1]>a[other2]){
                    move(other2,other1);
                }
                else move(other1,other2);
            }
        }
    }
    
    return 0;
}
void move(int now,int next){//柱子标号 
    a[next].push(a[now].top() );
    printf("%c->%c",s[now],s[next]);
    a[now].pop() ;  
}
  • 写回答

2条回答 默认 最新

  • LYSnowy 2022-01-26 16:24
    关注

    c语言是不支持stl库的,c++才可以使用stl,才可以include stack

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 2月6日
  • 已采纳回答 1月29日
  • 创建了问题 1月26日

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line