Php链表

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
<?php
/**
* Created by PhpStorm.
* User: Alex
* Date: 2019/5/13
* Time: 13:35
*/

class Node
{
public $data;
public $next;

public function __construct($data)
{
$this->data = $data;
$this->next = null;
}
}

class SingleLinkedList
{
private $header;

public function __construct($data)
{
$this->header = new Node($data);
}

public function addNode($data)
{
$newNode = new Node($data);
$newNode->next = $this->header->next;
$this->header->next = $newNode;
}

public function insertNode($item, $data)
{
$newNode = new Node($data);
$current = $this->findNode($item);
var_dump($current);
$newNode->next = $current->next;
$current->next = $newNode;
}

public function findNode($item)
{
$current = $this->header;
while ($current->data != $item) {
$current = $current->next;
}

return $current;
}

public function updateNode($old, $new)
{
$current = $this->header;

if ($current->next == null) {
return false;
}

while (!empty($current)) {
echo "$current->data \n";
if ($current->data == $old) {
$current->data = $new;
//$newNode = new Node($new);
//$newNode->next = $current->next;
//$current->next = $newNode;

break;
}
$current = $current->next;
}
}

//public function deleteNode($item){
// $current = $this->header;
// $next = null;
// while (!empty($current)) {
// echo "$current->data \n";
// if ($current->next->data == $item) {
//
// if ($current->next != null) {
// $next = $current->next;
// }
// $current->next = $next;
//
// break;
// }
// $current = $current->next;
// }
//}
}

$linkedList = new SingleLinkedList('root');
//$linkedList->addNode('node1');
//$linkedList->addNode('node2');
//$linkedList->addNode('node3');
var_dump($linkedList);
$linkedList->insertNode('root', "node1");
$linkedList->insertNode('node1', "node2");
$linkedList->insertNode('root', "node0");

$res = $linkedList->updateNode('node2','node22');
var_dump($res);
var_dump($linkedList);