The following COBOL code prepends a new node to an existing linked list of telephone numbers:
PERFORM 9000-ALLOCATE-TN.
*
IF FIRST-P = NULL
SET FIRST-P TO NEW-P
SET LAST-P TO NEW-P
ELSE
SET ALT-TN-NEXT-P TO FIRST-P
SET FIRST-P TO NEW-P.
*
SET NEW-P TO NULL.
If the list is initially empty, the procedure looks like this:
===>
Remember, 9000-ALLOCATE-TN allocated a new node and initialized it in ALT-TN-NODE, leaving ALT-TN-NEXT-P set to NULL. If the list is initially empty, we can leave ALT-TN-NEXT-P pointing to NULL because it will be the last node in the list (as well as the first node).
If the list already has one or more nodes in it, then the initial situation looks like this:
First we attach the new node to the head of the list:
Now the new node becomes the head of the list:
Finally we nullify NEW-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.