札记之PHP实现循环链表

循环链表和单向链表相似,节点类型都是一样的。唯一的区别是,在创建循环链表时,让其头节点的 next 属性指向它本身,即:head->next = head,换句话说,链表的尾节点指向头节点,形成了一个循环链表。

图示插入删除流程

插入

札记之PHP实现循环链表

删除

札记之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
class ListNode
{
private $data;
private $next;
public function __construct($data)
{
$this->data = $data;
}
public function __get($var)
{
return $this->$var;
}
public function __set($var, $val)
{
return $this->$var = $val;
}
}

// 循环链表类
class CircularLinkedList
{
private $head = NULL;
private $length = 0;
private $currentNode;

public function find($data = NULL)
{
$currentNode = $this->head;
if ($this->head !== NULL) {
while ($currentNode->data !== $data) {
$currentNode = $currentNode->next;
}
return $currentNode;
}
return false;
}

// 插入新节点
public function insert($data = NULL, $query = NULL)
{
$newNode = new ListNode($data);
if ($this->head) {
$currentNode = $this->find($query);
if ($currentNode->next !== $this->head) {
$currentNode->next = $newNode;
$newNode->next = $currentNode->next;
} else {
// 链表尾端
$currentNode->next = $newNode;
$newNode->next = $this->head;
}
} else {
$this->head = &$newNode;
}
$this->length++;
$newNode->next = $this->head;
return true;
}

// 删除节点
public function delete($data = NULL)
{
$currentNode = $this->head;
while ($currentNode->next != NULL && $currentNode->next->data != $data) {
$currentNode = $currentNode->next;
}
// 链表中间
if ($currentNode->next != $this->head) {
$currentNode->next = $currentNode->next->next;
} else {
// 链表尾端
$currentNode->next = $this->head;
}
}

public function display()
{
echo 'LinkList length: ' . $this->length . PHP_EOL;
$currentNode = $this->head;
while ($currentNode->next != $this->head) {
echo $currentNode->next->data . PHP_EOL;
$currentNode = $currentNode->next;
}
}
}

print("============插入=========== \n\r");
printf("插入节点33333, 44444, 55555 \n\r");
$CircularLinkObj = new CircularLinkedList();
$CircularLinkObj->insert(33333, 11111);
$CircularLinkObj->insert(44444, 33333);
$CircularLinkObj->insert(55555, 44444);
$CircularLinkObj->display();

print("============删除=========== \n\r");
printf("删除节点55555 \n\r");
$CircularLinkObj->delete(55555);
$CircularLinkObj->display();

运行结果:

1
2
3
4
5
6
7
8
9
============插入===========
插入节点33333, 44444, 55555
LinkList length: 3
44444
55555
============删除===========
删除节点55555
LinkList length: 3
44444
-------------本文结束感谢您的阅读-------------
坚持原创技术分享,您的支持将鼓励我继续创作!