A circular linked list is a type of linked list in which the last node points to the first, forming a complete circle of nodes. In other words, there is no null element at the end of this variant of the linked list.
Overall, this is really helpful in implementing the queue data structure.
It performs similarly to other linked list implementations in terms of performance, with the exception that traversing from the last node to the head node can be done in constant time. This is a linear procedure with traditional linked lists.
The insertion of new nodes is the first operation we'll go over. We'll have to deal with two scenarios when adding a new element:
The nextNode for tail will point to head in both of the examples above.
The next procedure we'll look at is searching to see if an element exists in the list. For this, we'll set the currentNode to a node in the list (typically the head) and traverse the entire list using the nextNode of this node until we discover the required element. Add a new containsNode method that takes the searchValue as a parameter:
After that, we'll have a look at the remove command. In general, after deleting an element, the prior node's nextNode reference must be updated to point to the nextNode reference of the node that was deleted. However, there are a few exceptions that must be considered:
In this final session, we'll take a look at traversing our circular linked list. We fix the currentNode as head and travel over the complete list using the nextNode of this node, similar to the search and remove procedures.
|