前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >实现php删除链表中重复的结点

实现php删除链表中重复的结点

作者头像
砸漏
发布2020-10-20 10:51:11
1.1K0
发布2020-10-20 10:51:11
举报
文章被收录于专栏:恩蓝脚本

删除链表中重复的结点:

定义两个指针pre和current

两个指针同时往后移动,current指针如果与后一个结点值相同,就独自往前走直到没有相等的

pre指针next直接指向current指针的后一个,把相同的都跳过

代码语言:javascript
复制
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
代码语言:javascript
复制
<?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);
代码语言:javascript
复制
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)的支持。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-12-16 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档