Skip to content

Commit facd478

Browse files
committed
Added search functionality to the linked list example
1 parent bcfecdc commit facd478

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

chap-03/linked-lists.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,4 +23,8 @@
2323
// Insert a new book as the first element of the list.
2424
$bookTitles->insertAtFirst("Introducing PHP to noobs");
2525

26-
$bookTitles->display();
26+
$bookTitles->display();
27+
28+
// Search for a existing title, and a non-existing title.
29+
var_dump($bookTitles->search("Introducing PHP to noobs")->data);
30+
var_dump($bookTitles->search("Clever stuff"));

src/Chapter03/LinkedList.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,4 +67,24 @@ public function insertAtFirst(string $data = NULL)
6767
return true;
6868
}
6969

70+
/**
71+
* Search for a node in the linked list.
72+
* We need to check if there are any nodes to begin with, and iterate through the list until found.
73+
* @param string|null $data
74+
* @return bool|ListNode
75+
*/
76+
public function search(string $data = NULL)
77+
{
78+
if ($this->_totalNodes) {
79+
$currentNode = $this->_firstNode;
80+
while ($currentNode !== NULL) {
81+
if ($currentNode->data === $data){
82+
return $currentNode;
83+
}
84+
$currentNode = $currentNode->next;
85+
}
86+
}
87+
return false;
88+
}
89+
7090
}

0 commit comments

Comments
 (0)