链表去重

来源:互联网 发布:淘宝怎么改收获地址 编辑:程序博客网 时间:2024/06/11 22:46

删除节点,也要删除这段对应的内存。。。。在php中使用unset....?垃圾回收机制??


2.2.4 Remove Duplicates from Sorted List

描述
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.

Given 1->1->2->3->3, return 1->2->3.

function f($l){    $p=$l->root->next;    if($l->root==null||$p==null) return false;    $value=$p->value;    $p1=$p;    $ps=$l->root;    $p=$p->next;    while($p!=null){        if($p->value==$p1->value){            $p1->next=$p->next;            $issame=true;        }else{            $p1=$p;       }     $p=$p->next;   } $l->showLink();}

2.2.5 Remove Duplicates from Sorted List II描述Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbersfrom the original list.For example,Given 1->2->3->3->4->4->5, return 1->2->5.Given 1->1->1->2->3, return 2->3.

这个题要多维护一个指针,删除重复数据的第一个


     
 function f($l)  {    $p=$l->root->next;    if($l->root==null||$p==null)   return  false;    $value=$p->value;    $p1=$p;    $ps=$l->root;    $p=$p->next;    $issame=false;    while($p!=null){        if($p->value==$p1->value){            $p1->next=$p->next;            $issame=true;        }else{          if($issame){             $ps->next=$p;             $p1=$p;             $issame=false;           }else{             $ps=$p1;             $p1=$p;           }       }     $p=$p->next;   }//end while   if($issame){      $ps->next=null;      }   $l->showLink();}

                                             
0 0
原创粉丝点击