As you learned in the Circular LinkedLists section, the only difference between Circular Linked Lists and Singly Linked Lists is that the last node of CLLs points to the head node again. We can simply modify the SLL implementation, so that last.next points to head instead of to null. It’s also more time efficient to store the location of the last node, instead of storing the location of head, so that you don’t have to traverse all the way down the list to add something to the end.
The new add() method looks similar to the previous one, but we set new_node.next to the head. Notice how we only store a reference to the last node, and we replaced “head” with “last.next” because it’s a circular list.
We need to change the toString() method, as well, again changing “head” to “last.next.”
Here’s some test code and it’s output:
Now you try!
If you play around with your newly-created class, it should display the same result as the SinglyLinkedList. However, there are some benefits to being able to iterate through CircularLinkedLists continuously. For example, if you had a list of tasks that you wanted your computer to continually cycle through, you could store the tasks in a CircularLinkedList, and this would be much more time efficient than other methods of storage.