May 2017
Intermediate to advanced
340 pages
8h 16m
English
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; } } }
Read now
Unlock full access