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

Recursion and linked lists

Many languages define linked lists as a primitive data structure, like arrays. These languages often encourage using recursion to process linked lists, because a linked list has a naturally recursive structure: each node points to null, or another node.

How would you define length recursively?

int length(ListNode *node) { }

Doubly linked lists

One other important variation on linked lists is to have list nodes point both to the next and the previous element. Among other things, this makes reverse traversal simple:

struct ListNode { int value; // For simplicity, assume a list of ints ListNode * next, *prev; }; class DoubleLinkedList { // some stuff, then: private: ListNode * head, * last; }; void DoubleLinkedList::printReverseOrder() { ListNode * current = last; while (current != NULL) { cout << current->value << endl; current = current->prev; } } // Can you define recursive deletion? void DoubleLinkedList::delete(ListNode *currentNode, int value) { // (you probably need more space than this) }

Last modified: Wed Jul 12 19:36:16 PDT 2000