Title Description
In a sorted linked list nodes duplicate, delete the duplicate node list, the node does not retain repeated, returns the head pointer list. For example, the list 1-> 2-> 3-> 3-> 4-> 4-> 5 is treated 1-> 2-> 5
Thinking
A node before the first node with a pointer pointing to pre repeats the list, with a pointer to another node repeats the last cur linked list, so that duplicate nodes encountered the pre-> next = cur-> next can delete all duplicate nodes. Because the entire list is likely to be repeated, it is necessary a pointer to the head node. code show as below:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead){
if(pHead==nullptr || pHead->next==nullptr)
return pHead;
ListNode* head = new ListNode(-1);
head->next = pHead;
ListNode* pre = head;
ListNode* cur = pHead;
while(cur!=nullptr){
if(cur->next!=nullptr && cur->val==cur->next->val){
while(cur!=nullptr && cur->next!=nullptr && cur->val==cur->next->val){
cur = cur->next;
}
pre->next = cur->next;
cur = cur->next;
}
else{
pre = pre->next;
cur = cur->next;
}
}
return head->next;
}
};