题目描述:
给定一个排序链表,要求删除链表中所有的重复结点.(例如: 1->2->2->3->3->4 处理后 1->4)
分析:
使用三个指针front、cur、last,初始时,front = NULL;cur = pHead;last = pHead->next;每一次判断cur->val == last->val .
1. 若相等,则last继续向后移动,直到第一个不等的结点或NULL;
* 当front = NULL 时,若last = NULL,直接返回NULL;若last != NULL,由于front = NULL代表从第一个结点开始到last所指向的结点之前结点都是重复结点,所以要移动pHead,是其指向last,并删除从cur开始到last之前的所有结点;
* 当front != NULL时,使front->next = last;并删除从cur开始到last之前的所有结点
2. 若不等,则cur = cur->next;last = last->next;
struct Node{
int val;
struct Node *next;
Node(int x = 0):val(x), next(NULL){}
};
Node *deleteDuplication(Node *pHead){
if(pHead == NULL || pHead->next == NULL)
return pHead;
Node *front = NULL;//当前结点的前驱
Node *cur = pHead;//当前结点
Node *last = pHead->next;//当前结点之后第一个val不同的结点
while(last != NULL){
if(cur->val == last->val){
while(last != NULL && last->val == cur->val)//跳过所有val相同的结点
last = last->next;
if(front == NULL){//处理特殊情况,当链表开始的若干结点val都想等时
if(last == NULL){//此时,又有last = NULL,即链表的所以节点的val都想等,则直接返回NULL
return NULL;
}else{//否则,使pHead=last,删除从cur开始到last之前的所有结点,并使得删除结束时cur=last;
pHead = last;
Node *tmp = NULL;
while(cur != last){
tmp = cur;
cur = cur->next;
delete [] tmp;
}
last = last->next;//删除结束后,让last指向cur之后的一个结点
}
}else{//当front不为NULL,只需要front->next = last, 再删除重复的结点即可
front->next = last;
Node *tmp = NULL;
while(cur != last){
tmp = cur;
cur = cur->next;
delete [] tmp;
}
if(last != NULL)
last = last->next;
}
}else{//即cur->val != last->val,则三个指针都向后移动一步
front = cur;
cur = cur->next;
last = last->next;
}
}
return pHead;
}