<?php
/*
* 链表的复制
* 输出了复制后的链表
* */
class RandomListNode{
var $label;
var $next = NULL;
function __construct($x){
$this->label = $x;
}
}
function MyClone($pHead)
{
$p = $pHead;//对象指向的是地址,所以可以保证链表改变后,$p指向链表的头部
//复制
while($pHead->next != null){
$temp = $pHead->next;
$pHead->next = new RandomListNode($pHead->label."·");//为了区分复制前后,在复制之后添加 .
$pHead->next->next = $temp;
$pHead = $pHead->next->next;
}
//剥除
$temp = new RandomListNode(null);//复制后的链表的头部
$res = $temp;//同理为了输出结果,留下一个指针指向节点头部
while($p->next != null){
$temp->next = $p->next;
$temp = $temp->next;//复制后的链表也需要前进
$p->next = $p->next->next;
$p = $p->next;
}
return $res;
}
//遍历
function fe($pHead){
while($pHead != null){
echo $pHead->label;
$pHead = $pHead->next;
}
}
//实例
$a = new RandomListNode(1);
$b = new RandomListNode(2);
$c = new RandomListNode(3);
$d = new RandomListNode(4);
$e = new RandomListNode(5);
$a->next = $b;
$b->next = $c;
$c->next = $d;
$d->next = $e;
//从1234 先变为 11.22.33.44.55 后分为 12345 和 1.2.3.4.5
$temp =MyClone($a);
fe($temp);
PHP 实现单链表的复制
最新推荐文章于 2022-12-26 16:03:34 发布