-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathcopy_complex_list.php
More file actions
100 lines (91 loc) · 2.29 KB
/
copy_complex_list.php
File metadata and controls
100 lines (91 loc) · 2.29 KB
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
<?php
/**
* 剑指 Offer 系列:复制复杂链表
* Author:学院君
*/
class ComplexListNode
{
/**
* 结点值
* @var string
*/
public $value;
/**
* 指向下一个结点
* @var ComplexListNode
*/
public $next = null;
/**
* @var ComplexListNode
*/
public $sibling = null;
}
/**
* 复制复杂链表实现函数
* @param ComplexListNode $sourceHead
* @return ComplexListNode
*/
function CloneComplexList(ComplexListNode $sourceHead): ComplexListNode
{
// 映射原始结点和目标结点
$map = [];
// 第一步:复制结点值和next指针
$node = $sourceHead;
$cloneHead = null;
while ($node != null) {
$clone = new ComplexListNode();
$clone->value = $node->value;
if ($node->next) {
$clone->next = clone $node->next;
}
$clone->sibling = null;
$map[$node->value] = $clone;
$node = $node->next;
if ($cloneHead == null) {
$cloneHead = $clone;
}
}
// 第二步:复制subling指针
$node = $sourceHead;
while ($node != null) {
$clone = $map[$node->value];
// 如果拷贝过来链表结点sibling指针收到next指针污染,将其清空
if ($clone->sibling != null) {
$clone->sibling = null;
}
if ($node->sibling != null) {
$clone->sibling = clone $map[$node->sibling->value];
}
$node = $node->next;
}
return $cloneHead;
}
// 测试代码
$nodeA = new ComplexListNode();
$nodeA->value = 'A';
$nodeB = new ComplexListNode();
$nodeB->value = 'B';
$nodeC = new ComplexListNode();
$nodeC->value = 'C';
$nodeD = new ComplexListNode();
$nodeD->value = 'D';
$nodeE = new ComplexListNode();
$nodeE->value = 'E';
$nodeA->next = $nodeB;
$nodeA->sibling = $nodeC;
$nodeB->next = $nodeC;
$nodeB->sibling = $nodeE;
$nodeC->next = $nodeD;
$nodeD->next = $nodeE;
$nodeD->sibling = $nodeB;
$head = $nodeA;
$cloneHead = CloneComplexList($head);
$cloneNode = $cloneHead;
while ($cloneNode != null) {
var_dump([
"value" => $cloneNode->value,
"next" => $cloneNode->next ? $cloneNode->next->value : "NULL",
"sibling" => $cloneNode->sibling ? $cloneNode->sibling->value : "NULL"
]);
$cloneNode = $cloneNode->next;
}