A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
深拷贝一个链表,这个链表除了一个next指针外,还包含一个random指针。
深度拷贝链表,会有链表指针指向的节点还未进行拷贝。
分三步对这个链表进行深拷贝:第一步,建立节点,并存放到与原节点一一对应的位置。第二步,拷贝random指针。第三步,拆分两个链表。具体代码如下:
<?php
class RandomListNode {
public $next = null;
public $random = null;
public $val;
public function __construct($val) {
$this->val = $val;
}
}
function copyRandomList($head) {
if ($head == null) {
return null;
}
//复制next指针
$node = $head;
while ($node !== null) {
$copyNode = new RandomListNode($node->val);
$copyNode->next = $node->next;
$node->next = $copyNode;
$node = $copyNode->next;
}
//复制random指针
$node = $head;
while ($node !== null) {
$copyNode = $node->next;
if ($node->random !== null) {
$copyNode->random = $node->random->next;
}
$node = $copyNode->next;
}
//拆分两个链表
$node = $head;
$copyNodeHead = $head->next;
while ($node !== null) {
$copyNode = $node->next;
$node->next = $copyNode->next;
$copyNode->next = $node->next->next;
$node = $node->next;
}
return $copyNodeHead;
}
$node1 = new RandomListNode(1);
$node2 = new RandomListNode(2);
$node3 = new RandomListNode(3);
$node4 = new RandomListNode(4);
$node5 = new RandomListNode(5);
$node6 = new RandomListNode(6);
$node1->next = $node2;
$node2->next = $node3;
$node3->next = $node4;
$node4->next = $node5;
$node5->next = $node6;
$node2->random = $node4;
$node4->random = $node1;
$copyNode = copyRandomList($node1);
while($node1 !== null) {
print '$node next节点:'.$node1->next->val.'random节点:'.$node1->random->val."\n";
$node1 = $node1->next;
}
while($copyNode !== null) {
print '$copyNode next节点:'.$copyNode->next->val.'random节点:'.$copyNode->random->val."\n";
$copyNode = $copyNode->next;
}