mirror of
				https://github.com/krahets/hello-algo.git
				synced 2025-11-04 14:18:20 +08:00 
			
		
		
		
	add forLoopRecur in recursion.c (#866)
This commit is contained in:
		@ -17,6 +17,25 @@ int recur(int n) {
 | 
				
			|||||||
    return n + res;
 | 
					    return n + res;
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					/* 使用迭代模拟递归 */
 | 
				
			||||||
 | 
					int forLoopRecur(int n) {
 | 
				
			||||||
 | 
					    int stack[1000]; // 借助一个大数组来模拟栈
 | 
				
			||||||
 | 
					    int top = 0;
 | 
				
			||||||
 | 
					    int res = 0;
 | 
				
			||||||
 | 
					    // 递:递归调用
 | 
				
			||||||
 | 
					    for (int i = n; i > 0; i--) {
 | 
				
			||||||
 | 
					        // 通过“入栈操作”模拟“递”
 | 
				
			||||||
 | 
					        stack[top++] = i;
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					    // 归:返回结果
 | 
				
			||||||
 | 
					    while (top >= 0) {
 | 
				
			||||||
 | 
					        // 通过“出栈操作”模拟“归”
 | 
				
			||||||
 | 
					        res += stack[top--];
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					    // res = 1+2+3+...+n
 | 
				
			||||||
 | 
					    return res;
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
/* 尾递归 */
 | 
					/* 尾递归 */
 | 
				
			||||||
int tailRecur(int n, int res) {
 | 
					int tailRecur(int n, int res) {
 | 
				
			||||||
    // 终止条件
 | 
					    // 终止条件
 | 
				
			||||||
 | 
				
			|||||||
		Reference in New Issue
	
	Block a user