数据结构06-栈和递归

数据结构06-栈和递归,第1张

汉诺塔:

#include
using namespace std;

int cnt = 0;

void move(int n,char a,char b)
{
	cout << ++cnt << " move disk " << n << " from " << a << " to " << b << endl;
}

void hanoi(int n,char a,char b,char c)
{
	if (n == 1)
	{
		move(1, a, c);
	}
	else
	{
		hanoi(n - 1, a, c, b);
		move(n, a, c);
		hanoi(n - 1, b, a, c);
	}
}


int main()
{
	hanoi(10, 'a', 'b', 'c');
	return 0;
}

递归累加:

#include
using namespace std;

long long sumto(int n)    //返回 0~n的总和
{
	if (n == 0)
	{
		return 0;
	}
	else
	{
		return n + sumto(n - 1);
	}
}

int main()
{
	cout << sumto(5) << endl;
}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/914860.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-16
下一篇2022-05-16

发表评论

登录后才能评论

评论列表(0条)

    保存