next up previous
Next: Inserting a new element Up: Unit 12 Previous: Searching an element in

Inserting a new element as the last one of a list

To insert elem as the last element of lis:

create a new node whose info field is elem;
if (lis is empty)
  return the list constituted only by the new node;
else {
  scan the list stopping when the current reference points to the last node
  concatenate the new node with the last one
}

The situation in memory after the scan of the list is finished and last references the last element of the list is shown below.

Iterative implementation:

  public static ListNode insertLast(ListNode lis, String s) {
    ListNode p = new ListNode();      // note: p.next == null
    p.info = s;

    if (lis == null)
      return p;                       // the list contains only the new node
    else {
      ListNode last = lis;
      while (last.next != null)       // find last element
        last = last.next;
      last.next = p;
      return lis;
    }
  }


next up previous
Next: Inserting a new element Up: Unit 12 Previous: Searching an element in