《leetCode-php》深拷贝带随机指针的链表

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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值