Skip to content

Commit b4a5de8

Browse files
committed
Added delete first node functionality to Linked List
1 parent 054252f commit b4a5de8

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

chap-03/linked-lists.php

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010

1111
require_once __DIR__ . '/../vendor/autoload.php';
1212

13+
define("SEPERATOR", PHP_EOL . "**********************************" . PHP_EOL);
14+
1315
$bookTitles = new LinkedList();
1416

1517
// Insert three books
@@ -19,6 +21,7 @@
1921

2022
// Display data
2123
$bookTitles->display();
24+
echo SEPERATOR;
2225

2326
// Insert a new book as the first element of the list.
2427
$bookTitles->insertAtFirst("Introducing PHP to noobs");
@@ -28,13 +31,22 @@
2831
// Search for a existing title, and a non-existing title.
2932
var_dump($bookTitles->search("Introducing PHP to noobs")->data);
3033
var_dump($bookTitles->search("Clever stuff"));
34+
echo SEPERATOR;
3135

3236
// Insert a title before another title
3337
$bookTitles->insertBefore("Handsome developers", "Programming Intelligence");
3438

3539
$bookTitles->display();
40+
echo SEPERATOR;
3641

3742
// Insert a title after another title
3843
$bookTitles->insertAfter("The complex anatomy of a developer", "Introduction to Algorithms");
3944

40-
$bookTitles->display();
45+
$bookTitles->display();
46+
echo SEPERATOR;
47+
48+
// Delete the first entry in the list
49+
$bookTitles->deleteFirst();
50+
51+
$bookTitles->display();
52+
echo SEPERATOR;

src/Chapter03/LinkedList.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,4 +144,22 @@ public function insertAfter(string $data = NULL, string $query = NULL)
144144
}
145145
}
146146

147+
/**
148+
* Deletes the first node of the nodelist, if applicable.
149+
* We need to make the second node the first node after removal.
150+
* @return bool
151+
*/
152+
public function deleteFirst() {
153+
if ($this->_firstNode !== NULL) {
154+
if ($this->_firstNode->next !== NULL) {
155+
$this->_firstNode = $this->_firstNode->next;
156+
} else {
157+
$this->_firstNode = NULL;
158+
}
159+
$this->_totalNodes--;
160+
return true;
161+
}
162+
return false;
163+
}
164+
147165
}

0 commit comments

Comments
 (0)