/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类
* @return ListNode类
*/
ListNode* deleteDuplicates(ListNode* head) {
// write code here
if(head == nullptr){
return head;
}
ListNode* newhead = new ListNode(-1);//设置一个初始链表
newhead->next = head;//将head链表添加到newhead中
ListNode* cur = newhead;
ListNode* p = head;
int count = 0;//设置重复次数
while(p->next && p){
if(p->val == p->next->val){//如果按照顺序,值相等
p->next = p->next->next;//删除该元素
count++;//将count次数加一再次进行判断
}else{
if(count > 0){
cur->next = p->next;//将该元素值全部删除
count = 0;
}else{
cur = p;
}
p = p->next;
}
}
if(count > 0){
cur->next = p->next;//存在比如{1,2,2},因为删除,所以上述循环条件不进行判断,在此额外进行判断
}
return newhead->next;
}
};