Skip to content

Commit 054252f

Browse files
committed
Added insert after specific node functionality to Linked List
1 parent 5e6523d commit 054252f

File tree

2 files changed

+39
-3
lines changed

2 files changed

+39
-3
lines changed

chap-03/linked-lists.php

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
$bookTitles = new LinkedList();
1414

1515
// Insert three books
16-
$bookTitles->insert("Introduction to Algortihms");
16+
$bookTitles->insert("Introduction to Algorithms");
1717
$bookTitles->insert("Introduction to PHP Data Structures");
1818
$bookTitles->insert("Programming Intelligence");
1919

@@ -29,7 +29,12 @@
2929
var_dump($bookTitles->search("Introducing PHP to noobs")->data);
3030
var_dump($bookTitles->search("Clever stuff"));
3131

32-
// Insert a title befor another title
32+
// Insert a title before another title
3333
$bookTitles->insertBefore("Handsome developers", "Programming Intelligence");
3434

35+
$bookTitles->display();
36+
37+
// Insert a title after another title
38+
$bookTitles->insertAfter("The complex anatomy of a developer", "Introduction to Algorithms");
39+
3540
$bookTitles->display();

src/Chapter03/LinkedList.php

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ public function search(string $data = NULL)
9393
* @param string|null $data
9494
* @param string|null $query
9595
*/
96-
public function insertBefore(string $data = null, string $query = null)
96+
public function insertBefore(string $data = NULL, string $query = NULL)
9797
{
9898
$newNode = new ListNode($data);
9999

@@ -113,4 +113,35 @@ public function insertBefore(string $data = null, string $query = null)
113113
}
114114
}
115115

116+
/**
117+
* Inserts a new node before an existing node.
118+
* Care must be taken to set the next values of the node after and the searched node itself
119+
* @param string|null $data
120+
* @param string|null $query
121+
*/
122+
public function insertAfter(string $data = NULL, string $query = NULL)
123+
{
124+
$newNode = new ListNode($data);
125+
126+
if ($this->_firstNode) {
127+
$nextNode = NULL;
128+
$currentNode = $this->_firstNode;
129+
while ($currentNode !== NULL) {
130+
if ($currentNode->data === $query) {
131+
if ($nextNode !== NULL) {
132+
$newNode->next = $nextNode;
133+
}
134+
$currentNode->next = $newNode;
135+
$this->_totalNodes++;
136+
break;
137+
}
138+
$currentNode = $currentNode->next;
139+
// We can only set the next Node if a value exists for next in the current node.
140+
if (isset($currentNode->next)) {
141+
$nextNode = $currentNode->next;
142+
}
143+
}
144+
}
145+
}
146+
116147
}

0 commit comments

Comments
 (0)