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

时间:2023-03-09 22:11:41
php实现删除链表中重复的节点

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

一、总结

二、php实现删除链表中重复的节点

题目描述:

在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5

三、总结

代码一:

 <?php
/*class ListNode{
var $val;
var $next = NULL;
function __construct($x){
$this->val = $x;
}
}*/
function deleteDuplication($pHead)
{
if($pHead==null){ //各种情况判断
return null;
}
if($pHead!=null&&$pHead->next==null){
return $pHead;
}
$cur = $pHead;
if($pHead->next->val==$pHead->val){
$cur = $pHead->next->next;
while($cur!=null&&$cur->val==$pHead->val){
$cur = $cur->next;
}
return deleteDuplication($cur);
}else{
$cur = $pHead->next;
$pHead->next = deleteDuplication($cur);
return $pHead;
}
}

代码二:没ac

 <?php
/*class ListNode{
var $val;
var $next = NULL;
function __construct($x){
$this->val = $x;
}
}*/
function deleteDuplication($pHead)
{
$head=new ListNode(-1);
$ans=$head;
$head->next=$pHead;
while($head){
if($head->next&&$head->next->next){
$l1=$head->next;
$l2=$l1->next;
while($l1->val==$l2->val){
$head->next=$l2->next;
if($l2->next) $l2=$l2->next;
else break;
}
$head=$head->next;
}
}
return $ans->next;
}

代码三:

 public static ListNode deleteDuplication(ListNode pHead) {

         ListNode first = new ListNode(-1);//设置一个trick

         first.next = pHead;

         ListNode p = pHead;
ListNode last = first;
while (p != null && p.next != null) {
if (p.val == p.next.val) {
int val = p.val;
while (p!= null&&p.val == val)
p = p.next;
last.next = p;
} else {
last = p;
p = p.next;
}
}
return first.next;
}

代码四:

 递归
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead)
{
if (pHead==NULL)
return NULL;
if (pHead!=NULL && pHead->next==NULL)
return pHead; ListNode* current; if ( pHead->next->val==pHead->val){
current=pHead->next->next;
while (current != NULL && current->val==pHead->val)
current=current->next;
return deleteDuplication(current);
} else {
current=pHead->next;
pHead->next=deleteDuplication(current);
return pHead;
}
}
};