Occasionally a program may need to scan a list to locate a particular
node, find a node that has a field with a particular value, or just print
the list.  Because lists are linked in both the forward and backward
directions, the list can be scanned from either the head or tail.

Here is a code fragment that uses a WHILE..WEND loop to print the names
of all nodes in a list:

    node& = PeekL&(list&, lh_Head&) 'get first node
    WHILE node& <> 0
      IF PeekL&(node&, ln_Succ&) <> 0 THEN 'avoid placeholder node
        PRINT RIGHT$("00000000" + HEX$(node&), 8); ": ";
        PRINT PeekSTR$(PeekL&(node&, ln_Name&), 0&) 'read out mstr& pointer
      END IF
      node& = PeekL&(node&, ln_Succ&)
    WEND

The example above will start with the first valid data node obtained from
the list headers lh_Head& field, and it will finally end up with the tail
placeholder node within the list header.
Now carfully notice the IF..THEN block, a common mistake is to process the
head or tail placeholder nodes within the (Min)ListHeader&, which do not
contain any data.  Valid data nodes have non-zero successor and predecessor
pointers.  Keeping this fact in mind, the above example can be simplified
and will even exclude the placeholder node at all:

    node& = PeekL&(list&, lh_Head&) 'get first node
    WHILE PeekL&(node&, ln_Succ&) <> 0 'avoid placeholder node
      PRINT RIGHT$("00000000" + HEX$(node&), 8); ": ";
      PRINT PeekSTR$(PeekL&(node&, ln_Name&), 0&) 'read out mstr& pointer
      node& = PeekL&(node&, ln_Succ&)
    WEND

This second example will start with the first valid data node, and end up
with the last valid data node.  If the list is empty, then the WHILE..WEND
loop is skipped at all and nothing is printed, because in empty lists the
lh_Head& field points to lh_Tail&, which is always zero.  That is, it will
appear as a zero ln_Succ& field in the current node, hence it is no valid
data node.

But now, after all the theory, another example using the FUNCTIONs GetHead&
and GetSucc& to do it the easy and correct way:

    node& = GetHead&(list&) 'get first node
    WHILE node& <> 0
      PRINT RIGHT$("00000000" + HEX$(node&), 8); ": ";
      PRINT PeekSTR$(PeekL&(node&, ln_Name&), 0&) 'read out mstr& pointer
      node& = GetSucc&(node&)
    WEND

Likewise, you can use the FUNCTIONs GetTail& and GetPred& to scan a list
backward from tail to head.  Once you are in the middle of a list you can
even go back and forth using GetSucc& and GetPred&. All of these FUNCTIONs
do already include the check for the placeholder nodes, hence they will
only return valid data nodes, or a zero result, if no more data nodes exist.
 
                                                     Back to List Functions