I am trying to write a function that removes duplicates from a linked list.
Here is the code I have:
If my input is 1,2,3,1,2,3 this function will remove the 1 and the 2, but will leave the duplicate 3. So my output will be 1,2,3,3.Code:/* * Function remove_dups() * * This function removes all duplicates from the list. Any node that is * removed is also freed. * */ void linklist::remove_dups() { node * current_ptr; node * prev_ptr; node * temp_ptr; current_ptr = _first_element; temp_ptr = _first_element->next; while (current_ptr != _last_element) { if (occurrences(current_ptr->data) == 1 && current_ptr->next != NULL) { current_ptr = current_ptr->next; } while (temp_ptr->data != current_ptr->data && temp_ptr->next != NULL) { temp_ptr = temp_ptr->next; if (temp_ptr == NULL) { current_ptr = current_ptr->next; break; } } if (current_ptr == _last_element) break; if (temp_ptr->data == current_ptr->data) { prev_ptr = _first_element; while (prev_ptr->next!= temp_ptr) { prev_ptr = prev_ptr->next; } prev_ptr->next = temp_ptr->next; _remove(temp_ptr); temp_ptr = _first_element; } } }
Any ideas why this is happening?
Brian