forked from TheAlgorithms/PHP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSinglyLinkedList.php
47 lines (36 loc) · 951 Bytes
/
SinglyLinkedList.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?php
/**
* Singly Linked List
*/
class SinglyLinkedList
{
public ?SinglyLinkedList $next = null;
public $data;
public function __construct($data)
{
$this->data = $data;
}
public function append($data): void
{
$current = $this;
while ($current instanceof SinglyLinkedList && isset($current->next)) {
$current = $current->next;
}
$current->next = new SinglyLinkedList($data);
}
public function delete($data): SinglyLinkedList
{
$current = $this;
if ($current->data == $data) {
return $current->next;
}
while ($current instanceof SinglyLinkedList && isset($current->next)) {
if ($current->next->data === $data) {
$current->next = $current->next->next;
return $this;
}
$current = $current->next;
}
return $this;
}
}