# C++ program to Replace Nodes with Duplicates in Linked List

In this article, we are given a linked list that contains elements from 1 to n and duplicates. Elements 1 to n will always be there with duplicates from [1..n]. We need to replace every duplicate element with n+1, n+2, and so on.

Lets consider an example

1→2→2→4→5→3→6→6

Next n = 42. So every duplicate is replaced with n+1, n+2, and so on. The next 42 is replaced with 47, and the next 46 is replaced with 48, leaving the first instance as it is.

First of all, we need to construct a binary tree in the main method as shown below −

Node* head = new Node(1);
solve(head);

Now the Nodes are as follows;

1→2→7→4→5→3→6→8

As we can observe, we need to keep track of the elements we saw to find the starting value of n. We also need a mechanism to figure out which elements are repeated to replace their values.

A proposed data structure that immediately comes to mind is set. We can traverse the linked list and push the elements into the set. After pushing elements in the set, we can find the last element, the largest element available in the linked list, as the set is a sorted data structure.

In the second traversal of the linked list, we can use the set as a hash. We will search each element in the set, and two conditions may occur.

• We find the element in the set and then remove it from the set, making it marked.

• We don't find the element in the set, and it means that we have already seen it from option one, and we will replace it with the next n.

## Example

To implement replacing the nodes with duplicate values in a linked list, follow the C++ program below. The C++ implementation makes use of the set data structure to traverse the linked list which in turn helps in searching for the duplicate elements.

#include <iostream>
#include <set>
using namespace std;
class Node {
public:
int value;
Node* next;
Node(int value) {
this->value = value;
next = NULL;
}
};
set<int> hash;
while(copy) {
hash.insert(copy->value);
copy = copy->next;
}
auto it = hash.end();
it--;
int startingN = *it +1;
} else {
}
}
}
cout << head->value << " ";
}
}
int main() {
cout << "Before: ";
cout << "\n";
cout << "After: ";
return 0;
}


## Output

Before: 41 42 42 44 45 43 46 46
After: 41 42 47 44 45 43 46 48


## Conclusion

We used the concept of hashing and found the largest element in the linked list with the help of a data structure set. We could have also used map or unordered_map as a hash.

Updated on: 10-Aug-2022

306 Views