LeetCode练习:在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。
如:链表1->2->3->3->4->4->5 处理后为 1->2->5
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead)
{
if(pHead==NULL||pHead->next==NULL){
return pHead;
}
if(pHead->next->next==NULL){
if(pHead->val==pHead->next->val){
free(pHead->next);
pHead->next=NULL;
free(pHead);
pHead=NULL;
}
return pHead;
}
//三指针法
ListNode* first=NULL;
ListNode* second=pHead;
ListNode* third=pHead->next;
ListNode* tmp=NULL;
ListNode* newhead=pHead;
while(third){
if(second->val==third->val){
while(second->val==third->val&&third){
tmp=third;
third=third->next;
free(tmp);
tmp=NULL;
}
tmp=second;
second=third;
free(tmp);
tmp=NULL;
if(first==NULL){
newhead=third;
}else{
first->next=third;
}
if(third==NULL){
return newhead;
}
third=third->next;
}else{
first=second;
second=third;
third=third->next;
}
}
return newhead;
}
};