4️⃣

16.4 Do it Yourself! - CirclyLinkedList

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.

image

We need to change the toString() method, as well, again changing “head” to “last.next.”

image

Here’s some test code and it’s output:

image
image

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.

Previous Section

Next Section

⚖️

Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.