-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkedList.php
91 lines (72 loc) · 1.8 KB
/
LinkedList.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
<?php
class Node{
public $data;
public $next;
}
class LinkedList{
public $head;
public function __construct()
{
$this->head = null;
}
public function PrintLinkedList()
{
$temp = $this->head;
if($temp==null){
echo 'LinkedList is empty';
}else
{
echo 'List contains : ';
while($temp!=null)
{
echo $temp->data.' - ';
$temp = $temp->next;
}
}
}
public function push_back($newElement)
{
$newNode = new Node();
$newNode->data = $newElement;
$newNode->next = null;
if($this->head==null)
{
$this->head = $newNode;
}else{
$temp = $this->head;
while($temp->next != null){
$temp = $temp->next;
}
$temp->next = $newNode;
}
}
public function pop_at($position)
{
if($position<1){
echo 'Position must be greater than 1';
}else if($position==1 && $this->head!=null){
$this->head = $this->head->next;
}else{
$temp = $this->head;
for($i=1;$i<$position-1;$i++)
{
if($temp!=null)
{
$temp = $temp->next;
}
}
if($temp != null && $temp->next != null) {
$temp->next = $temp->next->next;
} else {
//5. Else the given node will be empty.
echo "\nThe node is already null.";
}
}
}
}
$myList = new LinkedList();
$myList->push_back(10);
$myList->push_back(4);
$myList->push_back(15);
$myList->pop_at(2);
$myList->PrintLinkedList();