
Formally, this Traverse operation is an example of a passive iterator operation. An iterator is any operation that iterates through a data structure one element at a time; we call it passive because the client program simply calls it once and “stands back” passively while the iterator roams through the entire structure. In this note, we use the terms traversal and iteration interchangeably.
Sometimes an application requires iterating through a structure, touching each element once, but allowing the client program the flexibility to decide just when to proceed to the next element. Moving through a structure in this fashion is called active iteration, because the client program is actively involved in the process at every step.
For the case of singly-linked lists whose nodes contain elements of type ElementType, we will call these operations StartTraversal, AtEndOfList, MoveToNextElement, and RetrieveCurrentElement, respectively. If the list being used by the client is called MyList, and MyElement is a variable of type ElementType, then the basic client-program algorithm is
StartTraversal(MyList);
-- loop initialization
LOOP
EXIT WHEN AtEndOfList(MyList); -- loop termination
condition
MyElement := RetrieveCurrentElement(MyList);
-- process the current element MyElement here
MoveToNextElement(MyList);
-- loop incrementation step
END LOOP;
The implementation details of these operations depend upon the way the data structure is implemented. For linked lists, we include, as a field in the record defining the list type, an extra pointer, WhichElement, indicating which element of the list is being processed. In this implementation,