描述
Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.
Input: head = [1,2,3,3,4,4,5]
Output: [1,2,5]
Input: head = [1,1,1,2,3]
Output: [2,3]
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(head == nullptr || head->next == nullptr)
return head;
ListNode ans(0);
ListNode *first = &ans;
ans.next = head;
ListNode *prev = first->next;
ListNode *cur = prev->next;
if(prev->val == cur->val && cur->next == nullptr)
return nullptr;
while(cur){
bool del = false;
while(cur->val == prev->val && cur->next !=nullptr){
prev = cur;
cur = cur->next;
del = true;
}
if(prev->val == cur->val && cur->next == nullptr){
// delete cur;
// delete prev;
first->next = nullptr;
return ans.next;
}
if(del){
first->next = cur;
prev = cur;
cur = cur->next;
}
else {
first = first->next;
prev = cur;
cur = cur->next;
}
}
return ans.next;
}
};