Removing Duplicates from a Sorted Linked List

Algorithm:

[sourcecode lang=”cpp”]

void RemoveDuplicates(intnode* head) {
intnode* current = head;
if (current == NULL) return; // do nothing if the list is empty
// Compare current node with next node
while(current->next!=NULL) {
if (current->data == current->next->data) {
intnode* nextNext = current->next->next;
delete(current->next);
current->next = nextNext;
}
else {
current = current->next; // only advance if no deletion
}
}
}

[/sourcecode]

Leave a Reply

Your email address will not be published. Required fields are marked *