I try to remove duplicates from a linked list using hashing. Not with unordered_map but using a vector for tracking the occurrences. I run a simple test case and I get a result that I don't understand.
My code is :
class Solution {
public:
Node* removeDuplicates(Node *head) {
vector<int> vec{10000 , 0};
auto tmp = head;
auto tmp2 = tmp;
while (tmp) {
vec[tmp->data]++;
cout << "Data : " << tmp->data << " counter " << vec[tmp->data] << "\n";
if (vec[tmp->data] > 1) {
tmp2->next = tmp2->next->next;
}
tmp2 = tmp;
tmp = tmp->next;
}
return head;
}
I tried the following test case 2 3 3 4 6. This are the data for the nodes in the linked list.
And the result I get is this.
Data : 2 counter 1
Data : 3 counter 1
Data : 3 counter 2
Data : 4 counter 1
Data : 6 counter 4114
2 3 4
The actual result should have been
Data : 2 counter 1
Data : 3 counter 1
Data : 3 counter 2
Data : 4 counter 1
Data : 6 counter 1
2 3 4 6