Lesson contents

Circular linked lists

The last node links back to the first. Keep a stopping rule, such as counting visits or returning to the starting node.

Simple example

Follow four turns starting at 2. After 6 the link leads back to 2 again.

Start2→4→6
Result2 4 6 2
lesson.mojo
def main():
    var values: List[Int] = [2, 4, 6]
    var following: List[Int] = [1, 2, 0]
    var node = 0
    var turn = 0
    while turn < 4:
        print(values[node])
        node = following[node]
        turn += 1
Output
2
4
6
2
Advertisements

Everyday examples

Rotate class helpers

Helpers A, B and C take turns. A starts. Who takes the fourth turn?

StartA B C
ResultA

Three turns complete one trip around the ring. The next link returns to A.

Ride a circular shuttle

The stops are 4, 9 and 12. You board at 12. Which stop is next?

Start4 9 12
Result4

The last stop is linked to the first. You reach stop 4 without reversing direction.

Repeat a slideshow once

Slides 7, 3 and 8 repeat. Which slides should a one-cycle preview show if it starts at 3?

Start7 3 8
Result3 8 7

Count three slides and stop. Continuing until there is no next slide would keep the preview running.

Cost and limits

A ring has no final empty link. Following next until it is empty would never finish in a nonempty ring.