Inserting before a specific node

This process is similar to the first operation that we looked at. The main difference is that we need to find out the specific node and then insert a new node before it. 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 the node following the newly created node so that it points to the node that we searched for. This is shown in the following image:

Here is the code to implement the logic shown earlier:

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

if ($this->_firstNode) {
$previous = NULL;
$currentNode = $this->_firstNode;
while ($currentNode !== NULL) {
if ($currentNode->data === $query) {
$newNode->next = $currentNode;
$previous->next = $newNode;
$this->_totalNode++;
break;
}
$previous = $currentNode;
$currentNode = $currentNode->next;
}
}
}

If we inspect the preceding code, we can see that the logic is pretty straightforward. We have two parameters in this method: one is the data and one is the query. We iterate through each node. While doing this, we also track the current node and previous node. It is important to track the previous node as we will set the next of previous node to a newly created node when our target node is found.

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

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