汉诺塔的非递归实现(使用c++堆栈stack实现)

汉诺塔的非递归实现

题目

在这里插入图片描述

答案

#include<stack>
#include<iostream>
using namespace std;
struct node{
	int n,a,b,c;
	node(int m,int x,int y,int z):n(m),a(x),b(y),c(z){}
}; 
int main()
{
	int n;
	cin>>n;
	stack<node> s;
	s.push(node(n,'a','b','c'));
	while(!s.empty())
	{
		node t=s.top();
		s.pop();
		if(t.n==1) printf("%c -> %c\n",t.a,t.c);
		else
		{
			s.push(node(t.n-1,t.b,t.a,t.c));
			s.push(node(1,t.a,t.b,t.c)); 
			s.push(node(t.n-1,t.a,t.c,t.b));
		}
	}
}

问题总结

  1. push的内容为node(n,‘a’,‘b’,‘c’),不能像递归一样直接输入n,‘a’,‘b’,‘c’
  2. 记得输出时加上回车
  3. 在使用堆栈函数是不要忘了堆栈名,即s.push()而不是push()
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
汉诺塔问题的非递归实现需要借助栈来完成。下面是C语言实现非递归汉诺塔算法: ```c #include <stdio.h> #include <stdlib.h> typedef struct _stack { int *data; // 存储栈中的数据 int top; // 栈顶位置 int capacity; // 栈的容量 } stack; // 创建一个指定容量的栈 stack *createStack(int capacity) { stack *s = (stack *)malloc(sizeof(stack)); s->data = (int *)malloc(sizeof(int) * capacity); s->top = -1; s->capacity = capacity; return s; } // 判断栈是否为空 int isStackEmpty(stack *s) { return s->top == -1; } // 判断栈是否已满 int isStackFull(stack *s) { return s->top == s->capacity - 1; } // 入栈 void push(stack *s, int value) { if (isStackFull(s)) { printf("Stack overflow.\n"); return; } s->data[++s->top] = value; } // 出栈 int pop(stack *s) { if (isStackEmpty(s)) { printf("Stack underflow.\n"); return -1; } return s->data[s->top--]; } // 汉诺塔非递归实现 void hanoi(int n) { stack *s = createStack(n); int i, x, step = 0; for (i = n; i >= 1; i--) { push(s, i); } while (!isStackEmpty(s)) { x = pop(s); step++; if (isStackEmpty(s)) { printf("Move disk %d from A to C.\n", x); continue; } push(s, x); if (step % 2 == 1) { x = pop(s); push(s, x); printf("Move disk %d from A to B.\n", x); } else { x = pop(s); push(s, x); printf("Move disk %d from B to C.\n", x); } } free(s->data); free(s); } int main() { int n; printf("Please input the number of disks: "); scanf("%d", &n); hanoi(n); return 0; } ``` 该算法使用了一个栈来存储盘子,并对盘子进行移动。具体实现过程可以参考代码注释。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值