Download presentation
Presentation is loading. Please wait.
1
Introduction to C Programming CE00312-1 Lecture 21 Recursion and Linear Linked Lists
2
Factorial of an Integer Factorial of 6 is expressed as 6! whose value is6 5 4 3 2 1 or it can be rewritten as6 5! We have defined 6! in terms of 5! - a recursive definition In general n! is n (n-1)! when n > 0 and 0! is 1
3
Factorial as a C function int fact (int n) { if (n == 0) { return 1; } else { return n * fact(n - 1); }
4
An equivalent “functional” version is: int fact(int n) { return (n == 0 ? 1 : n * fact(n - 1)); } This can be read as “return the result of if n is 0 then 1 else factorial of n-1”.
5
Recursion with Linear Linked Lists Recursive functions are more convenient, shorter and easier to modify (once you get used to them!) compared to iterative functions (ie with while loops).
6
Printing a linear linked list Print 3 then 35812 - list Print the rest
7
Recursive function print_list #include "LLL.h“// node structure, type void print_list(Listpointer list) { if (list != NULL)// not empty list { printf("%d\n", list -> value);// print first print_list(list -> next);// print rest }// else empty list do nothing } For the current node given by, pointer list, print its value and then the recursive call, print_list, deals with the rest.
8
Printing a linear linked list in reverse Print the rest in reverse then print 3 35812 - list
9
Print the list in reverse #include "LLL.h“// node structure, type void print_reverse(Listpointer list) { if (list != NULL)// not empty list { print_reverse(list -> next);// print rest printf("%d\n", list -> value);// print first }// else empty list do nothing } This function recurses down the list, including the last, and prints values as it returns back up the list.
10
Adding the items in a linear linked list 3+sum of the rest 35812 - list
11
Recursive function to add all the items in a list int sum(Listpointer list) { if (list == NULL) { return 0;// empty list, sum is 0 } else { return list->value + sum(list->next); }
12
The previous function could also be written as: int sum(Listpointer list) { return (list == NULL) ? 0 : list -> value + sum(list -> next); } This can be read as “return the result of if the list is empty then zero else this node’s value plus the sum of the rest”
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.