LinkedList: Why would there be a loop?

I was wondering in what situations could a linked list have a loop?

To test the hasLoop() method we have to intentionally create a LinkedList with a loop (basically make a mistake in our linking). The end user of this class would not have access to make this mistake because first and last are private. So either we made a mistake in our code which we need to fix, or an end user is modifying the class code, or there is a LinkedList that came from another source and was not created by our class.

Are there other situations I’m not thinking of where we could end up with a loop in our LinkedList? Or is this exercise strictly for the sake of exercise?

I thought what if we give the ability to create a LinkedList with a loop but I’m not sure what the use case would be. And if I could think of a use case, I think I would have to re-write all methods in the class to deal with the possibility of a loop existing.

Anyone have thoughts on this?

Thanks,

Off the top of my head, a simple case where a (doubly) linked list with a loop is useful: days of the week. Imagine applications like figuring out previous and next day. Or having a method to determine what day of the week it will be in X days (granted, there may be more efficient ways to do this). Or having an iterator that keeps printing out the “next” day of the week forever.

Basically, do not be so quick to assume there is “no use” in having a LinkedList with a loop.

1 Like

Besides @jmrunkle response, Mosh also give us an example, like when you put a Music Player on repeat. When the last music is reached you need go back to the first position/music (Circular)