>>108436581
recursion just means that a function can call itself. its useful when working with data structures that contain nodes, like graphs and lists. dfs algorithms are also naturally written with recursion vs bfs which do not. you can also build a return value using stack frames. here is a stupid simple example in c.
#include <stdio.h>
#include <stdlib.h>
struct node {
int val;
struct node* next;
};
void free_list(struct node* head)
{
if (!head)
return;
struct node* next = head->next;
free(head);
free_list(next);
}
struct node* cons(int val, struct node* head)
{
struct node* n = malloc(sizeof(struct node));
*n = (struct node){ .val = val, .next = head };
return n;
}
int add_one(int val)
{
return val + 1;
}
struct node* map(int (*f)(int), struct node* head)
{
if (!head)
return NULL;
return cons(f(head->val), map(f, head->next));
}
void print_list(struct node* head)
{
if (!head) {
printf("\n");
return;
}
printf("%d ", head->val);
print_list(head->next);
}
int main()
{
struct node* list = cons(1, cons(2, cons(3, cons(4, cons(5, NULL)))));
struct node* inc_list = map(add_one, list);
print_list(list);
print_list(inc_list);
free_list(list);
free_list(inc_list);
return 0;
}