value); }"> value); }">

Presentation is loading. Please wait.

Presentation is loading. Please wait.

Recursion.

Similar presentations


Presentation on theme: "Recursion."— Presentation transcript:

1 Recursion

2 Recursion on Linked Lists
Use the following struct: struct node { int value; struct node *next; }; Write a function that takes a pointer to a linked list, and prints the ints in the nodes in reverse order (i.e., print the value in the last node first.) void printRev(struct node *list) { if list isn't null: Print the sublist consisting of all but the first node Print the first node if (list == null) return; printRev(list->next); printf(" %d", list->value); }

3 Recursion on Linked Lists
Write a recursive function that returns the sum of the int values in the nodes of a linked list int sumList(struct node *list) { Write a recursive function that returns true if the int num is in the linked list, and false otherwise bool searchList(struct node *list, int num) { if list == null return 0 return list->value + sumList(list->next); ------ if list is null return false if list ->value === num return true return searchList(list->next);

4 Recursion on Linked Lists
Write a recursive function that inserts specified value in a new node at the end of the linked list. Return a pointer to the linked list. struct node *insertLast(struct node *list, int num) { struct node *temp; if list == NULL { Create new node, return pointer to it} list->next = insertLast(list->next, num);

5 Recursion on Linked Lists
Write a function that removes the last node in a linked list. Your function will do nothing if the list is empty. Return a pointer to the linked list. Return NULL if the list is empty. struct node *removeLast(struct node *list) { if(list == NULL) return NULL; if(list -> next == NULL) { free(list); return NULL; } list->next = removeLast(list->next); return list;


Download ppt "Recursion."

Similar presentations


Ads by Google