欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

實(shí)現(xiàn)php刪除鏈表中重復(fù)的結(jié)點(diǎn)

 更新時(shí)間:2018年09月27日 14:18:39   投稿:laozhang  
在本篇文章中,我們給大家?guī)砹岁P(guān)于php刪除鏈表中重復(fù)的結(jié)點(diǎn)的相關(guān)知識點(diǎn)內(nèi)容以及相關(guān)代碼,有興趣的朋友們參考下。

刪除鏈表中重復(fù)的結(jié)點(diǎn):

定義兩個(gè)指針pre和current

兩個(gè)指針同時(shí)往后移動,current指針如果與后一個(gè)結(jié)點(diǎn)值相同,就獨(dú)自往前走直到?jīng)]有相等的

pre指針next直接指向current指針的后一個(gè),把相同的都跳過

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;
    }  
}
//構(gòu)造一個(gè)帶重復(fù)的鏈表
$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;//當(dāng)前都指向第一個(gè)結(jié)點(diǎn)
    $current=$pHead->next;//當(dāng)前結(jié)點(diǎn)是第一個(gè)結(jié)點(diǎn)
    while($current!=null){
        //如果當(dāng)前結(jié)點(diǎn)值和當(dāng)前結(jié)點(diǎn)的下一個(gè)結(jié)點(diǎn)值相同
        if($current->next!=null && $current->data==$current->next->data){
            //保存當(dāng)前結(jié)點(diǎn)值
            $val=$current->data;
            //當(dāng)前結(jié)點(diǎn)往后移直到和下一個(gè)結(jié)點(diǎn)值不相等
            while($current->next!=null && $val==$current->next->data){
                $current=$current->next;
            }  
            //前一個(gè)指針next直接指向當(dāng)前結(jié)點(diǎn)的next
            $pre->next=$current->next;
        }  
        //兩個(gè)指針同時(shí)后移
        $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
   }
  }
 }
}

以上就是實(shí)現(xiàn)php刪除鏈表中重復(fù)的結(jié)點(diǎn)的全部內(nèi)容和代碼,感謝大家對腳本之家的支持。

相關(guān)文章

最新評論