next up previous
Next: Deleting the first element Up: Unit 12 Previous: Operations on linked lists

Inserting a new element as the first one of a list

To insert a new element as the first one of a list: -

  1. we allocate a new node for the element (note that we are given the element (e.g., a string), but we still must create the node for it),
  2. we assign the element to the info instance field,
  3. we concatenate the new node with the original list,
  4. we make the newly created node the first one of the list.

Note that we do not need to actually access the elements of the list to perform this operation.

Implementation:

public static ListNode insertFirst(ListNode lis, String s) {
  ListNode p = new ListNode();     // 1
  p.info = s;                      // 2
  p.next = lis;                    // 3
  lis = p;                         // 4
  return lis;
}


next up previous
Next: Deleting the first element Up: Unit 12 Previous: Operations on linked lists