To visit each item in a linked list one after another, according to the linked list’s inherent sequence, you can use the following algorithm.
ptr = Start
WHILE ptr <> 0
OUTPUT Data(ptr)
ptr = Next(ptr)
END WHILE
When applied to the list illustrated above, the algorithm runs as follows:
- The value of ptr is set to Start, in this case 6 (Abigail)
- The loop will iterate while ptr is not 0.
- The item in the Data array given by the value of ptr (Abigail) is output first
- The value of ptr is then changed to 3, which is the item Abigail is pointing to next (Beatrix)
- Next time through the loop, Beatrix is output.
- The value of ptr is then changed to 1, which is the item Beatrix is pointing to next (Chloe)
- Next time through the loop, Chloe is output.
- The value of ptr is then changed to 4, which is the item Chloe is pointing to next (David)
- Next time through the loop, David is output.
- The value of ptr is then changed to 5, which is the item David is pointing to next (Edward)
- Next time through the loop, Edward is output.
- The value of ptr is then changed to 2, which is the item Edward is pointing to next (Francis)
- Next time through the loop, Francis is output.
- The value of ptr is then changed to 0, which is the item Francis is pointing to next, but 0 represents the end of the list.
- The loop ends.