'C++ Function (RemoveSortedDuplicates) not deleting more than one duplicated node
I want to write a function that returns true if there are nodes with duplicated values and removed successfully in a sorted singly linked list, else it returns false. When I test it at main() like this:
int main() {
struct node* head = NULL;
struct node* head1 = NULL;
struct node* head2 = NULL;
AddToEndv2(&head, 1);AddToEndv2(&head, 2);AddToEndv2(&head, 3);AddToEndv2(&head, 4);AddToEndv2(&head, 5);AddToEndv2(&head, 15);AddToEndv2(&head, 70);
//AddToEndv2(&head1, 30);AddToEndv2(&head1, 40);AddToEndv2(&head1, 50);AddToEndv2(&head1, 40);AddToEndv2(&head1, 30);AddToEndv2(&head1, 30);
Print(head);
cout << "\n";
//Print(head1);
//cout << "\n";
cout << "RemoveDuplicatesSorted function output:" << endl;
cout << RemoveDuplicatesSorted(head);
cout << "\n";
Print(head);
cout << "\n";
I get this output, where it does not delete more than one duplicate node. Neither does it return false when there are no duplicate values:
1
2
3
4
5
15
70
RemoveDuplicatesSorted function output:
0
1
2
3
4
5
15
70
This is my function:
bool RemoveDuplicatesSorted(struct node* head){
struct node* current = head;
bool result = false;
while (current != NULL && current->next != NULL){
if (current->data == current->next->data){
struct node* temp = current->next;
current->next = current->next->next;
delete temp;
result=true;
}
else
{
current = current->next;
}
}
current=nullptr;
return result;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
