The following COBOL code inserts a new node before the node to which CURR-P points (we should have already verified that CURR-P is not NULL):
PERFORM 9000-ALLOCATE-TN.
*
IF FIRST-P = CURR-P
SET FIRST-P TO NEW-P
ELSE
PERFORM 9200-FIND-PREV-NODE
IF PREV-P = NULL
DISPLAY 'INTERNAL ERROR! CURRENT NODE IS NOT ON THE LIST'
ELSE
SET ADDRESS OF TN-NODE TO PREV-P
SET TN-NEXT-P TO NEW-P.
*
SET ALT-TN-NEXT-P TO CURR-P.
*
SET NEW-P TO NULL.
SET PREV-P TO NULL.
Remember, 9000-ALLOCATE-TN allocates a new node and initializes it
in ALT-TN-NODE, leaving ALT-TN-NEXT-P set to NULL. The situation may
then look like this:
Whatever points to the current node must be made to point to the new node instead. If the current node is the first in the list, we redirect FIRST-P. Otherwise we perform 9200-FIND-PREV-NODE, which searches the list to find the previous node. It returns a pointer to the previous node in PREV-P.
Note the (rather primitive) error-handling when PREV-P is NULL. In this case the so-called current node isn't on the list; hence we cannot insert anything before it. In most cases we should treat this situation as a fatal error, because it indicates a major logical flaw somewhere else in the code.
If we ignore this unhappy possibility, and ignore the chance that we are inserting prior to the first node, we have the following picture:
In the example illustrated, the previous node turned out to be the
first node in the list, but this fact is not important.
Next we point the previous node to the new node, which becomes its successor:
Then we point the new node to its successor (formerly the successor of the previous node):
Finally we nullify NEW-P and PREV-P:
This last step is not really necessary, but it's good hygiene. If you keep an extra copy of a pointer longer than you need to, it may lead you into a pitfall later.
Pointer Traps