C-Language/Recursion

Recursion examples in C language

Soul-Learner 2016. 11. 22. 16:14

C 언어에서 함수의 재귀호출(Self-Invocation) 예


C 언어로 구현한 링크드 리스트에 저장된 각 노드의 값을 합산할 때 재귀호출을 이용하는 예

#include <stdio.h>

struct Node
{
	int num;
	struct Node *prevNode;
	struct Node *nextNode;
} ;

int recursive(struct Node *);

int main()
{
	struct Node root = { 0,NULL,NULL };
	struct Node node1 = { 1, &root, NULL };
	root.nextNode = &node1;
	struct Node node2 = { 2, &node1, NULL };
	node1.nextNode = &node2;
	struct Node node3 = { 3, &node2, NULL };
	node2.nextNode = &node3;
	struct Node node4 = { 4, &node3, NULL };
	node3.nextNode = &node4;
	struct Node node5 = { 5, &node4, NULL };
	node4.nextNode = &node5;

	int total = recursive(&root);

	printf("리스트의 값 합산결과:%d \n", total);
	return 0;
}

int recursive(struct Node *pNode) {
	if(pNode != NULL)
		return pNode->num + recursive(pNode->nextNode);
	else return 0;
}