-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinked_list.php
115 lines (90 loc) · 1.77 KB
/
linked_list.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
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
110
111
112
113
114
<?php
class Node {
public $data;
public $next = NULL;
public function __construct ($data) {
$this->data = $data;
}
public function getData() {
return $this->data;
}
public function getNext() {
return $this->next;
}
}
class LinkedList {
private $head = NULL;
private $count = 0;
public function InsertAtFirst($data) {
$head = new Node($data);
if($this->head === NULL ) {
$this->head = new Node($data);
} else {
$head->next = $this->head;
$this->head = $head;
}
$this->count++;
return;
}
public function InsertAtLast($data) {
if($this->head == NULL) {
return $this->InsertAtFirst($data);
}
$tail = $this->head;
while($tail->next) {
$tail = $tail->next;
}
$tail->next = new Node($data);
$this->count++;
}
public function InsertAtNthLocation($data,$n) {
if($this->head == NULL) {
return $this->InsertAtFirst($data);
}
$tail = $this->head;
while($tail->next) {
$tail = $tail->next;
}
$tail->next = new Node($data);
$this->count++;
}
public function push($data) {
return $this->InsertAtLast($data);
}
public function pop() {
if($this->count && $this->head) {
$tail = $this->head;
if($tail->next) {
while($tail->next->next) {
$tail = $tail->next;
}
$result = $tail->next->data;
$tail->next = NULL;
} else {
$result = $tail->data;
$this->head = NULL;
}
$this->count--;
return $result;
}
throw Exception("List is empty");
}
}
/*
$list = new LinkedList();
$list->push(1);
$list->push(2);
$list->push(3);
echo $list->pop()."\n";
echo $list->pop()."\n";
echo $list->pop()."\n";
$list->InsertAtFirst(23);
$list->push(8);
$list->push(11);
echo $list->pop()."\n";
$list->push(1);
echo $list->pop()."\n";
echo $list->pop()."\n";
echo $list->pop()."\n";
*/
?>