Inserting after a specific node

This process is similar to the inserted a node before a target node. The difference is that we need to insert the new node after the target node. Here, we need to consider the target node as well as the next node, to which it's pointing. When we find the target node, we can change the next node so that it points to the newly created node, and then we can change node following the newly created node so that it points to the next node following the target node. Here is the code used to implement this:

    public function insertAfter(string $data = NULL, string $query = 
NULL) {
$newNode = new ListNode($data);

if ($this->_firstNode) {
$nextNode = NULL;
$currentNode = $this->_firstNode;
while ($currentNode !== NULL) {
if ($currentNode->data === $query) {
if($nextNode !== NULL) {
$newNode->next = $nextNode;
}
$currentNode->next = $newNode;
$this->_totalNode++;
break;
}
$currentNode = $currentNode->next;
$nextNode = $currentNode->next;
}
}
}
..................Content has been hidden....................

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