Example. Summing up a List of Integers

[comp1110-2U]

Recursive data types like linked lists are usually best handled by recursive functions:

int sum(IntList l) { if(l == null) { return 0; // base case } else { return l.value + sum(l.rest); //recursive case } }

However, in this case, because the last step performed in all recursive cases is to invoke the function recursively, We can translate the above program into a loop:

int sumLoop(IntList l) { int sum = 0; // running total of list while(l != null) { // INV: sum is sum of values of all list nodes from original l to current l (exclusive) sum = sum + l.value; l = l.rest; } return sum; }

This works by starting at the first list cell, adding its value to the running total, then moving to the next cell by adjusting l to be l.next, and repeating until we reach null.

bars magnifying-glass caret-down plus minus arrow-right xmark