[   ^ to index...   |   <-- previous   |   next -->   ]

Recursion and linked lists

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:

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); } } }

Last modified: Wed Jul 12 18:52:05 PDT 2000