Skip to content

Commit 291741d

Browse files
committed
Added delete last node functionality to Linked List
1 parent b4a5de8 commit 291741d

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

chap-03/linked-lists.php

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,13 @@
4646
echo SEPERATOR;
4747

4848
// Delete the first entry in the list
49-
$bookTitles->deleteFirst();
49+
var_dump($bookTitles->deleteFirst());
50+
51+
$bookTitles->display();
52+
echo SEPERATOR;
53+
54+
// Delete the last entry in the list
55+
var_dump($bookTitles->deleteLast());
5056

5157
$bookTitles->display();
5258
echo SEPERATOR;

src/Chapter03/LinkedList.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,4 +162,30 @@ public function deleteFirst() {
162162
return false;
163163
}
164164

165+
/**
166+
* Deletes the last node of the nodelist, if applicable.
167+
* We need to make sure the next property of the second last is set to NULL.
168+
* @return bool
169+
*/
170+
public function deleteLast()
171+
{
172+
if ($this->_firstNode !== NULL){
173+
$currentNode = $this->_firstNode;
174+
if ($currentNode->next === NULL){
175+
$this->_firstNode = NULL;
176+
} else {
177+
$previousNode = NULL;
178+
179+
while ($currentNode->next !== NULL) {
180+
$previousNode = $currentNode;
181+
$currentNode = $currentNode->next;
182+
}
183+
$previousNode->next = NULL;
184+
$this->_totalNodes--;
185+
return true;
186+
}
187+
}
188+
return false;
189+
}
190+
165191
}

0 commit comments

Comments
 (0)