CSC300 / CSC402: Nullable Recursion [5/5] Previous pageContents

11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  public void insert (double item) {  



    first = insertH (first, item);

  }
  private static Node insertH (Node x, double item) { 
    if (x == null || x.item >= item) {
      return new Node (item, x);
    } else {
      x.next = insertH (x.next, item);
      return x;
    }
  }

Easiest to write, once you understand it.

We don't know if a new node will be created in the helper!

Therefore, it's important that the helper function return something back to its caller, and the caller always update the appropriate pointer.

Even if a pointer ends up not being changed, the caller doesn't know if it needs to be changed, so it must unconditionally do the assigment of the pointer!

Some common mistakes:

  • Forget to update first in the starter.
  • Forget to update x.next in the helper.
  • Forget to return x in the helper.

Previous pageContents