汉诺塔问题,递归很简单,用非递归实现

一个问题:所有递归函数都能非递归化吗?
答案是肯定的。可以借助栈和循环实现
题目如图:
汉诺提非递归实现
在这里,直接调用了c++ STL的栈stack,当然,也可以自己编写个简单的栈,几行代码的事,见第二段代码。

问题1:在提交PAT上运行时,N=20时,发现超时,修改方案:
将cout改成printf,cin改成scanf,这样会提高速度,引用头文件
直接通过

#include<iostream>
#include<stack>
using namespace std;

struct Node {
	int N;
	char origin;
	char middle;
	char dest;
};
void Hanoi(int);
int main() {
	int n;
	cin >> n;
	Hanoi(n);
	return 0;
}
void Hanoi(int N) {
	stack<Node> s;
	struct Node node = { N,'a','b','c' };
	s.push(node);//栈的初值
	while (!s.empty()) {
		struct Node node0 =s.top();
		s.pop(); 
		if (node0.N == 1) {
			cout << node0.origin << " -> " << node0.dest << endl;
		} else {
			struct Node node1 = { node0.N - 1,node0.origin,node0.dest,node0.middle };
			struct Node node2 = { 1,node0.origin,node0.middle,node0.dest };
			struct Node node3 = { node0.N - 1,node0.middle,node0.origin,node0.dest };
			//入栈的顺序是反的哦,先解决的问题后入栈
			s.push(node3);
			s.push(node2);
			s.push(node1);
		}
	}
}

以下代码使用自己编写一个简单的栈。

#include<iostream>
#include<cstdio>
#define MAXSIZE 100
//将cout改成printf就跑通了

struct Node {
	int N;
	char origin;
	char middle;
	char dest;
};
typedef struct SNode* Stack;
struct SNode {
	struct Node* data;
	int top;
	int MaxSize;
};

void Hanoi(int);
Stack createStack(int MaxSize);
void push(Stack s, struct Node node);
bool empty(Stack s);
struct Node pop(Stack s);

int main() {
	int n;
	scanf("%d", &n);
	Hanoi(n);
	return 0;
}

void Hanoi(int N) {

	Stack s = createStack(MAXSIZE);
	struct Node node = { N,'a','b','c' };
	push(s, node);//栈的初值
	while (!empty(s)) {
		struct Node node0 = pop(s);
		if (node0.N == 1) {
			printf("%c -> %c\n", node0.origin, node0.dest);
			//cout << node0.origin << " -> " << node0.dest << endl;
		} else {
			struct Node node1 = { node0.N - 1,node0.origin,node0.dest,node0.middle };
			struct Node node2 = { 1,node0.origin,node0.middle,node0.dest };
			struct Node node3 = { node0.N - 1,node0.middle,node0.origin,node0.dest };
			//入栈的顺序是反的哦,先解决的问题后入栈
			push(s, node3);
			push(s, node2);
			push(s, node1);
		}
	}
}

Stack createStack(int MaxSize) {
	Stack s = new struct SNode;
	s->data = new struct Node[MaxSize];
	s->MaxSize = MaxSize;
	s->top = -1;
	return s;
}

void push(Stack s, struct Node node) {
	//简化版,不担心栈满
	s->data[++(s->top)] = node;
}
struct Node pop(Stack s) {

	return s->data[(s->top)--];
}
bool empty(Stack s) {
	return (s->top == -1);
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值