Skip to content

Commit 5e6523d

Browse files
committed
Added insert before specific node functionality to Linked List
1 parent facd478 commit 5e6523d

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

chap-03/linked-lists.php

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,9 @@
2727

2828
// Search for a existing title, and a non-existing title.
2929
var_dump($bookTitles->search("Introducing PHP to noobs")->data);
30-
var_dump($bookTitles->search("Clever stuff"));
30+
var_dump($bookTitles->search("Clever stuff"));
31+
32+
// Insert a title befor another title
33+
$bookTitles->insertBefore("Handsome developers", "Programming Intelligence");
34+
35+
$bookTitles->display();

src/Chapter03/LinkedList.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,4 +87,30 @@ public function search(string $data = NULL)
8787
return false;
8888
}
8989

90+
/**
91+
* Inserts a new node before an existing node.
92+
* Care must be taken to set the next values of the node before and the searched node itself to match the inserted node
93+
* @param string|null $data
94+
* @param string|null $query
95+
*/
96+
public function insertBefore(string $data = null, string $query = null)
97+
{
98+
$newNode = new ListNode($data);
99+
100+
if ($this->_firstNode) {
101+
$previous = NULL;
102+
$currentNode = $this->_firstNode;
103+
while ($currentNode !== NULL) {
104+
if ($currentNode->data === $query) {
105+
$newNode->next = $currentNode;
106+
$previous->next = $newNode;
107+
$this->_totalNodes++;
108+
break;
109+
}
110+
$previous = $currentNode;
111+
$currentNode = $currentNode->next;
112+
}
113+
}
114+
}
115+
90116
}

0 commit comments

Comments
 (0)