Building circular linked list

Building a circular linked list is not at as hard as it sounds from the name. So far, we have seen that adding a new node at the end is pretty simple; we set the next reference of the last node to NULL. In a circular linked list, the last node's next reference will actually point to the first node, thereby creating a circular list. Let's write a simple circular linked list where the nodes will be inserted at the end of the list:

class CircularLinkedList { 

private $_firstNode = NULL;
private $_totalNode = 0;

public function insertAtEnd(string $data = NULL) {
$newNode = new ListNode($data);
if ($this->_firstNode === NULL) {
$this->_firstNode = &$newNode;
} else {
$currentNode = $this->_firstNode;
while ($currentNode->next !== $this->_firstNode) {
$currentNode = $currentNode->next;
}
$currentNode->next = $newNode;
}
$newNode->next = $this->_firstNode;
$this->_totalNode++;
return TRUE;
}
}

If we look closely look at the preceding code, it looks exactly like our singly linked list implementation. The only difference is that we do not check the end of the list, rather than making sure the current node is not the same as the first node. Also, in the following line, we assign the next reference of the newly created node to the first node of the list:

$newNode->next = $this->_firstNode; 

As we are implementing this, the new nodes are added to the back of the list. All we need to do is set the new node's next reference to our first node in the list. By doing so, we have actually created a circular linked list. We have to make sure that we do not run- in an infinite loop. That is why we are comparing $currentNode->next to $this->_firstNode. The same principle will apply when we are displaying all elements in the circular linked list. We need to ensure that we do not fall in an infinite loop while displaying the titles. Here is the code that will display all titles from a circular linked list:

    public function display() { 
echo "Total book titles: " . $this->_totalNode . " ";
$currentNode = $this->_firstNode;
while ($currentNode->next !== $this->_firstNode) {
echo $currentNode->data . " ";
$currentNode = $currentNode->next;
}

if ($currentNode) {
echo $currentNode->data . " ";
}
}

So far, we have built a singly linked list and implemented a circular linked list. Now, we will implement a doubly linked list with PHP.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset