Build a Linked List

The following algorithm inserts new items into the linked list shown.

Store new item at NextFree pointer
Identify new item’s place in list
IF new start item THEN
            Set new item’s pointer to previous start value
            Reset start to new item
ELSE
            Temporarily store preceding item’s pointer
            Set preceding item’s pointer to point to the new item
            Set new item’s pointer to preceding item’s old pointer
END IF
Increment NextFree pointer

How the algorithm works

Each new data item is placed in the Data array, unconditionally, at the position given by NextFree.

The place of the new item in the linked list is then identified (this is detailed in the pseudocode)

If it is a new starting item, then its pointer is set to that of the existing starting item, and the existing starting item’s pointer is set to the new item.

If on the other hand the new item belongs in between a pair of existing items, then the existing item which comes before the new item must have its pointer adjusted so that it points to the new item, and the existing item that comes after the new item must now be pointed to by the new item.  This means that the preceding item’s pointer has to be stored temporarily before it is overwritten, so the new item can take over from the preceding item.

When the new item is in place, NextFree is incremeneted in readiness for the next insertion.

 

 

 

pointer of the preceding item (the one that must come before it) is stored temporarily, because the new item must take over from it.