Inserting before a specific node

Inserting before a specific node requires us to find the node first, and based on its position, we need to change the next and previous nodes for the new node, the target node, and the node before the target node, as follows:

    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;
$currentNode->prev = $newNode;
$previous->next = $newNode;
$newNode->prev = $previous;
$this->_totalNode++;
break;
}
$previous = $currentNode;
$currentNode = $currentNode->next;
}
}
}
..................Content has been hidden....................

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