Appending to a Linked List

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

The following COBOL code appends 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 ADDRESS OF TN-NODE TO LAST-P
        SET TN-NEXT-P          TO NEW-P
        SET LAST-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. We can leave ALT-TN-NEXT-P pointing to NULL because it will be the last node in the list.

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 tail of the list to the new node:

[attach new node]

Now the new node becomes the last node of the list:

[redirect LAST-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