/
index.php
95 lines (86 loc) · 1.62 KB
/
index.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
<?php
class Node
{
public $value, $prev, $next;
public function __construct($value)
{
$this->value = $value;
}
}
class DoublyLinkedList
{
public $head, $tail;
public function __construct()
{
$this->head = null;
$this->tail = null;
}
public function add_node($value)
{
$newNode = new Node($value);
$pointer = $this->head;
if ($pointer == null)
{
$this->head = $newNode;
$this->tail = $newNode;
$this->head->prev = null;
$this->head->next = null;
}
else
{
while($pointer->next)
{
$pointer = $pointer->next;
}
$pointer->next = $newNode;
$newNode->prev = $pointer;
$newNode->next = null;
$this->tail = $newNode;
}
}
public function delete_node($value)
{
$pointer = $this->head;
while($pointer->value != $value)
{
$pointer = $pointer->next;
}
$pointer->prev->next = $pointer->next;
$pointer->next->prev = $pointer->prev;
if (isset($pointer->next->next->next))
{
$pointer->next->next = $pointer->next->next->next;
}
else
{
$pointer->next->next = null;
}
}
public function insert_after($value, $node_value)
{
$pointer = $this->head;
$newNode = new Node($value);
While($pointer->value != $node_value)
{
$pointer = $pointer->next;
}
$newNode->prev = $pointer;
$newNode->next = $pointer->next;
$pointer->next->prev = $newNode;
$pointer->next = $newNode;
}
public function displayAll()
{
var_dump($this->head);
var_dump($this->head->next);
return $this;
}
}
$list = new DoublyLinkedList();
$list->add_node(1);
$list->add_node(2);
$list->add_node(3);
$list->delete_node(2);
$list->insert_after(2,1);
var_dump($list);
?>