栈->栈与递归

文字简述

1.阶乘函数

栈->栈与递归

 

2.2阶Fiibonacci数列

栈->栈与递归

 

3.n阶Hanoi塔问题

栈->栈与递归

 

代码实现

 

栈->栈与递归
 1 //
 2 // Created by lady on 19-4-3.
 3 //
 4 
 5 #include <stdio.h>
 6 #include <stdlib.h>
 7 #include <string.h>
 8 
 9 static int Fact(int n)
10 {
11     if(n==0){
12         return 1;
13     }else{
14         return n*Fact(n-1);
15     }
16 }
17 
18 static int Fibonacci(int n)
19 {
20     if(n == 0){
21         return 0;
22     }else if(n == 1){
23         return 1;
24     }else{
25         return (Fibonacci(n-1) + Fibonacci(n-2));
26     }
27 }
28 
29 // 将塔座x上按直径由小到大且自上而下编号为1至n的n个圆盘按规则搬到塔座z上,y可作辅助塔座
30 // 搬动操作move(x, n, z)可定义为(c是初值为0的全局变量,对搬动计数)
31 // printf("%d. Move disk %d from %c to %c", ++c, n, x, z);
32 int C = 0;
33 static int move(char x, int n, char z)
34 {
35     printf("step %d: move disk %d from %c to %c\n", ++C, n, x, z);
36     return 0;
37 }
38 static int hanoi(int n, char x, char y, char z)
39 {
40     if(n == 1){
41         move(x, n, z);
42     }else{
43         hanoi(n-1, x, z, y);
44         move(x, n, z);
45         hanoi(n-1, y, x, z);
46     }
47     return 0;
48 }
49 int main(int argc, char *argv[])
50 {
51     printf("5! = %d\n", Fact(5));
52     printf("Fibonacci(5) = %d\n", Fibonacci(5));
53     hanoi(3, 'a', 'b', 'c');
54     return 0;
55 }
栈和递归

 

 

 代码运行

 

/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

 

上一篇:剑指offer 7. 递归和循环 斐波那契数列


下一篇:斐波那契数列