In a circular linked list the last node of the list does not contain a reference or link to null, but rather a link to the first node (head) of the list. Comparing the Circular Linked list to a common LinkedList we cant help but notice a few advantages such as the ease of traversing the List by starting from any point we choose, it can also be useful when implementing a queue because we can maintain a pointer to the last inserted node and the front can always be obtained as next of the last. Probably the most common application of a Circular Linked List is how applications run in a pc, as they are cycled to give them each a small amount of time to be executed by the processor.
Example
This example demonstrates how to build a single-link circular linked list using
Node class
Our Node class is the foundation on which we will build our linked list, so it is very important to define all the necessary attributes that we will use later one, in this case as an example we will only work with a parameter id, to store some kind of id (school id for example), but more parameters can be easily added, it is also important to note that we will begin to work with links or pointers at this time, and in our constructor we will assign this pointer to None (null) because we are not building the list just yet.
class Node: |
CircularLinkedList class
Our circular linked list class is not more than a collection of methods utilized to alter in many different ways our circular linked list, here we can include methods such as: add(), delete(), find(), traverse(), print_list(), etc. in this example we will explore two methods: add() and print_list(), but more can be easily implemented, it is important to note that more often than note recursion is a good way of building this methods, although iteration tends to be faster, as this is a beginner example we will use iteration for the methods listed above.
class CircularLinkedList: |
CircularLinkedList instance
Finally we create a new instance of out CircularLinkedList, add a couple of values and print our list to check if its working correctly (note that we will be printing the head value last to debug that our list is working correctly).
list = CircularLinkedList() #create a new CircularLinkedList |
Output
Our output should look something like this.
1->2->3->1 |
Check this project on GitHub.