Presentation is loading. Please wait.

Presentation is loading. Please wait.

Recursion repetition without loops. Recursion  definition solving a problem in terms of a smaller version of itself  form of a recursive solution: base.

Similar presentations


Presentation on theme: "Recursion repetition without loops. Recursion  definition solving a problem in terms of a smaller version of itself  form of a recursive solution: base."— Presentation transcript:

1 Recursion repetition without loops

2 Recursion  definition solving a problem in terms of a smaller version of itself  form of a recursive solution: base case(s) recursive case(s)

3 Recursion examples for IntNode class  find maximum data value in list int maxValue; if (head != null) maxValue = head.maxData(); head 1326541950 419 maxData

4 Recursion examples for IntNode class public class IntNode { private int data; private IntNode link; public IntNode(int d, IntNode n) { data = d; link = n; }

5 Max value in linked list public int maxData () // non-recursive version { int max = data; IntNode cursor = link; while (cursor != null) { if (cursor.data > max) max = cursor.data; cursor = cursor.link; } return max; }

6 Max value in linked list public int maxData () // recursive version { if (link == null) return data; int maxOfRest = link.maxData(); return Math.max(maxOfRest, data); }

7 Sum of values in linked list public int sumData () // non-recursive version { int sum = data; IntNode cursor = link; while (cursor != null) { sum += cursor.data; cursor = cursor.link; } return sum; }

8 Sum of values in linked list public int sumData () // recursive version { if (link == null) return data; return data + link.sumData(); }

9 Other examples:  search for a value in list two base cases  count occurrences of a value in a list  make a reverse copy of a list

10 a recursive method wrapper // a static method public static IntNode reverseList(IntNode head) { if (head == null) return null; return head.reverse(null); }

11 make a reverse copy of a list public IntNode reverse(IntNode prefix) { IntNode copyThis = new IntNode(data, prefix); if (link == null) // no more nodes return copyThis; return link.reverse(copyThis); }

12 Other uses of recursive processing  directory traversals % ls -R  puzzle solutions towers of Hanoi


Download ppt "Recursion repetition without loops. Recursion  definition solving a problem in terms of a smaller version of itself  form of a recursive solution: base."

Similar presentations


Ads by Google