Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
The following is my code:
ListNode *getNextElement(ListNode *head, bool& repeated){
while ((head->next) != NULL &&
(head->val == head->next->val)){
head = head->next;
repeated = true;
}
return head->next;
}
ListNode *deleteDuplicates(ListNode *head) {
ListNode *result = NULL;
ListNode *copy_result = result;
ListNode *next = NULL;
for (ListNode *cur = head; cur != NULL; cur = next){
bool cur_repeat = false;
next = getNextElement(cur, cur_repeat);
if (cur_repeat == true){
while(cur!=next){
ListNode *toFree = cur;
cur = cur->next;
delete toFree;
}
}
else{
if(result == NULL){
result = cur;
copy_result = result;
}
else{
result->next = cur;
result = result->next;
}
}
}
if(result != NULL)
result->next = NULL;
return copy_result;
}