Prepending to a Linked List

(The following discussion uses data names and procedure names defined elsewhere.)

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:

[empty list] ===> [one-node list]

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:

[3-node list]

First we attach the new node to the head of the list:

[attach new node]

Now the new node becomes the head of the list:

[redirect FIRST-P]

Finally we nullify NEW-P:

[point NEW-P to NULL]

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.


[home]COBOL Home [structure] Data Structures