/* From Cracking the Coding Interview 2-1 */
/* Write code to remove duplicates from an unsorted linked list.
How would you solve this
problem if a temporary buffer is not allowed? */
void removeDuplicates(node * head) {
if (head == nullptr ||
head->next == nullptr) {
return;
}
node * p = head;
node * currentNode = nullptr;
node * nextNode = nullptr;
while (p != nullptr) {
currentNode = p;
nextNode =
currentNode->next;
while (nextNode != nullptr) {
if (p->value
== nextNode->value) {
currentNode->next
= nextNode->next;
nextNode->next = nullptr;
nextNode =
currentNode->next;
} else {
currentNode
= currentNode->next;
nextNode =
nextNode->next;
}
}
p = p->next;
}
}
No comments:
Post a Comment