CSC300 / CSC402: Non-Nullable Recursion [3/5] Previous pageContentsNext page

It's more typical to check base case first in a recursive function.

Note that lines 12-13 and 19-20 look almost exactly the same!

The only difference is we're working with first in the starter function and x.next in the helper function.

11
12
13
14
15
16
17
18
19
20
21
22
23
24
  public void insert (double item) {  
    if (first == null || first.item >= item) {
      first = new Node (item, first);
    } else {
      insertH (first, item);
    }
  }
  private static void insertH (Node x, double item) { 
    if (x.next == null || x.next.item >= item) {
      x.next = new Node (item, x.next);
    } else {
      insertH (x.next, item);
    }
  }

Computes forwards

A single function call both:

  • creates the new node
  • puts it in its place

Previous pageContentsNext page