-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinked-list.php
More file actions
109 lines (92 loc) · 2.49 KB
/
linked-list.php
File metadata and controls
109 lines (92 loc) · 2.49 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<?php
class Node {
public $data;
public $next;
public function __construct($data) {
$this->data = $data;
$this->next = null;
}
}
class LinkedList {
private $head;
public function __construct() {
$this->head = null;
}
public function insertAtBeginning($data) {
$newNode = new Node($data);
$newNode->next = $this->head;
$this->head = $newNode;
}
public function insertAtEnd($data) {
$newNode = new Node($data);
if (!$this->head) {
$this->head = $newNode;
return;
}
$current = $this->head;
while ($current->next) {
$current = $current->next;
}
$current->next = $newNode;
}
public function insertAfterNode($prevData, $data) {
$current = $this->head;
while ($current && $current->data !== $prevData) {
$current = $current->next;
}
if (!$current) {
return "$prevData not found.";
}
$newNode = new Node($data);
$newNode->next = $current->next;
$current->next = $newNode;
}
public function deleteNode($key) {
$current = $this->head;
if ($current && $current->data === $key) {
$this->head = $current->next;
return;
}
$prev = null;
while ($current && $current->data !== $key) {
$prev = $current;
$current = $current->next;
}
if (!$current) {
return "$key not found.";
}
$prev->next = $current->next;
}
public function traverse() {
$result = [];
$current = $this->head;
while ($current) {
$result[] = $current->data;
$current = $current->next;
}
return $result;
}
public function __toString() {
$result = [];
$current = $this->head;
while ($current) {
$result[] = $current->data;
$current = $current->next;
}
return $result ? implode(" -> ", $result) : "Empty List";
}
}
// Example usage
$linkedList = new LinkedList();
$linkedList->insertAtBeginning(10);
$linkedList->insertAtEnd(20);
$linkedList->insertAtEnd(30);
$linkedList->insertAfterNode(20, 25);
echo "Linked List after insertions:\n";
echo $linkedList . "\n";
echo "\nTraversed List:\n";
print_r($linkedList->traverse());
$linkedList->deleteNode(25);
echo "\nLinked List after deletion:\n";
echo $linkedList . "\n";
?>