栈->栈与递归

文字简述

1.阶乘函数

栈->栈与递归

2.2阶Fiibonacci数列

栈->栈与递归

3.n阶Hanoi塔问题

栈->栈与递归

代码实现

 //
// Created by lady on 19-4-3.
// #include <stdio.h>
#include <stdlib.h>
#include <string.h> static int Fact(int n)
{
if(n==){
return ;
}else{
return n*Fact(n-);
}
} static int Fibonacci(int n)
{
if(n == ){
return ;
}else if(n == ){
return ;
}else{
return (Fibonacci(n-) + Fibonacci(n-));
}
} // 将塔座x上按直径由小到大且自上而下编号为1至n的n个圆盘按规则搬到塔座z上,y可作辅助塔座
// 搬动操作move(x, n, z)可定义为(c是初值为0的全局变量,对搬动计数)
// printf("%d. Move disk %d from %c to %c", ++c, n, x, z);
int C = ;
static int move(char x, int n, char z)
{
printf("step %d: move disk %d from %c to %c\n", ++C, n, x, z);
return ;
}
static int hanoi(int n, char x, char y, char z)
{
if(n == ){
move(x, n, z);
}else{
hanoi(n-, x, z, y);
move(x, n, z);
hanoi(n-, y, x, z);
}
return ;
}
int main(int argc, char *argv[])
{
printf("5! = %d\n", Fact());
printf("Fibonacci(5) = %d\n", Fibonacci());
hanoi(, 'a', 'b', 'c');
return ;
}

栈和递归

代码运行

/home/lady/CLionProjects/untitled/cmake-build-debug/untitled
5! = 120
Fibonacci(5) = 5
step 1: move disk 1 from a to c
step 2: move disk 2 from a to b
step 3: move disk 1 from c to b
step 4: move disk 3 from a to c
step 5: move disk 1 from b to a
step 6: move disk 2 from b to c
step 7: move disk 1 from a to c Process finished with exit code 0
上一篇:递归转手工栈处理的一般式[C语言]


下一篇:用js来实现那些数据结构05(栈02-栈的应用)