Many languages define linked lists as a primitive data structure, like arrays. These languages often encourage the use of recursion to process linked lists. Recall that a linked list has a naturally recursive structure: each node points to NULL, or the next node.
The formula for doing an operation on the linked list recursively is therefore:
- Null base case(s): If we have the null list, return failure (usually).
- Inductive case(s): Process the current node and then recursively perform the procedure on the remainder of the list.
Given our list definition from the previous pages, can you define an operation to sum all the items in a list, recursively?
int sumList(ListNode *node) { } How would you define append recursively? (This will require a slightly different base case.)
void appendList(ListNode *node, int value) { } Now, can you describe what the following recursive procedure does?
int foo(ListNode *node, bool flag) { if (node == NULL) { return 0; } else { if (flag) { return node->value + foo(node->next, !flag); } else { return foo(node->next, !flag); } } }