Circular linked list
Last updated
Was this helpful?
Last updated
Was this helpful?
Circular linked list is a linked list where all nodes are connected to form a circle. There is no NULL at the end. A circular linked list can be a singly circular linked list or doubly circular linked list. - geeksforgeeks.org
Fig: Circular Single Linked List
Fig: Circular Doubly Linked List
All methods will same as single linked list. Only overwrite the insert, push and removeAt methods
The CircularLinkedList class does not need and additional properties, so we can simply extend the LinkedList Class, only overwrite the required methods.
Push method will append an element at the end of the LinkedList. While appending an element (node), There are two scenarios : 1. LinkedList is Empty.
set the linked list head property to the new node.
set new node's next to the head, since circular LinkedList doesn't have a NULL pointer at the end.
LinkedList is Not Empty.
loop till the end.
set the End node to the new node i.e end node.next to the node.
set new node's next to the head.
after pushing an element to linked list increment the counter
Insert method will insert an element at a given position. The position must be greater than zero and less than or equal to count (length of LinkedList). If not return undefined. 1. The index is Zero
Empty
Same as push method condition, when LinkedList is empty
Not Empty
set the new node to the current head
head to the new node
The index is equal to count .ie length of LinkedList
Get the (index - 1) element using the getElementAt method, store as the previous Element.
Set previous to the new node. And node's next to the head.
The index is greater than Zero
Get the (index - 1) element using the getElementAt method, store as the previous Element.
The indexed element will be previous. next, store as current.
Set previous to the new node. And node's next to previous.
after pushing an element to linked list increment the counter
RemovAt method will remove an element at a given position. The position must valid the index's out of bound error, by checking that the position is greater than and equal to zero and less than count. If not return undefined. 1. LinkedList is Empty
return undefined
The index is Zero.
Move the head to the next node. 3. The index is equal to the count - 1.
Get the (index - 1) element using the getElementAt method, store as the previous Element.
Set the previous's next to the head.
The index is greater than Zero
Get the (index - 1) element using the getElementAt method, store as the previous Element.
The indexed element will be previous.next, store as current.
set the previous.next to the current.next.
after removing an element from the linked list decrement the counter
Get the full source code here
Complexity will be the same as Single Linked List. This blog only covers a singly circular linked list. But the doubly circular linked list will similar to the doubly linked list.