82. Remove Duplicates from Sorted List II
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(head == NULL || head->next == NULL) return head;
ListNode* p = head;
ListNode* q = p->next;
head = new ListNode();
ListNode* t = head;
bool flag = true;
while(p != NULL && q != NULL) {
while(q != NULL && q->val == p->val) {
flag = false;
q = q->next;
}
if(flag) {
t->next = p;
t = p;
}
flag = true;
p = q;
if(q != NULL) q = q->next;
}
t->next = p;
return head->next;
}
};
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode* new_head = new ListNode();
ListNode* p = new_head;
p->next = head;
while(p->next) {
ListNode* q = p->next;
while(q->next && q->val == q->next->val) q = q->next;
if(p->next == q) p = q;
else p->next = q->next;
}
return new_head->next;
}
};