删除链表中重复的结点:
定义两个指针pre和current
两个指针同时往后移动,current指针如果与后一个结点值相同,就独自往前走直到没有相等的
pre指针next直接指向current指针的后一个,把相同的都跳过
pre=linkList
current=linkList
while current!=null
if current- data==current- next- data
value=current- data
while value==current- next- data
current=current- next
pre- next=current- next
pre=pre- next
current=current- next
return linkList
<?php
class Node{
public $data;
public $next;
public function __construct($data=""){
$this- data=$data;
}
}
//构造一个带重复的链表
$linkList=new Node();
$linkList- next=null;
$temp=$linkList;
$node1=new Node(2);
$temp- next=$node1;
$temp=$node1;
$node2=new Node(2);
$temp- next=$node2;
$temp=$node2;
$node3=new Node(3);
$temp- next=$node3;
$temp=$node3;
$node4=new Node(3);
$temp- next=$node4;
$temp=$node4;
$node5=new Node(4);
$temp- next=$node5;
$node5- next=null;
function deleteDuplication($pHead){
$pre=$pHead- next;//当前都指向第一个结点
$current=$pHead- next;//当前结点是第一个结点
while($current!=null){
//如果当前结点值和当前结点的下一个结点值相同
if($current- next!=null && $current- data==$current- next- data){
//保存当前结点值
$val=$current- data;
//当前结点往后移直到和下一个结点值不相等
while($current- next!=null && $val==$current- next- data){
$current=$current- next;
}
//前一个指针next直接指向当前结点的next
$pre- next=$current- next;
}
//两个指针同时后移
$pre=$pre- next;
$current=$current- next;
}
return $pHead;
}
var_dump($linkList);
$result=deleteDuplication($linkList);
var_dump($result);
object(Node)#1 (2) {
["data"]=
string(0) ""
["next"]=
object(Node)#2 (2) {
["data"]=
int(2)
["next"]=
object(Node)#3 (2) {
["data"]=
int(2)
["next"]=
object(Node)#4 (2) {
["data"]=
int(3)
["next"]=
object(Node)#5 (2) {
["data"]=
int(3)
["next"]=
object(Node)#6 (2) {
["data"]=
int(4)
["next"]=
NULL
}
}
}
}
}
}
object(Node)#1 (2) {
["data"]=
string(0) ""
["next"]=
object(Node)#2 (2) {
["data"]=
int(2)
["next"]=
object(Node)#4 (2) {
["data"]=
int(3)
["next"]=
object(Node)#6 (2) {
["data"]=
int(4)
["next"]=
NULL
}
}
}
}
以上就是实现php删除链表中重复的结点的全部内容和代码,感谢大家对ZaLou.Cn的支持。