Can someone give me some explanation on the answer for the question below? •Writ
ID: 3830581 • Letter: C
Question
Can someone give me some explanation on the answer for the question below?
•Write a recursive function that removes the duplicates in a list of integers.
•We assume that the list is sorted in ascending order.
void removeDuplicates(list<int>& list_1, list<int>::iterator& itr){
if (itr == list_1.end()|| ++itr==list_1.end()) //if we hit the end or the last element
return;
--itr; //regress it because you advanced it
list<int>::iterator current = itr;
if (*current == *(++itr))
list_1.erase(current);
removeDuplicates(list_1, itr);
}
Explanation / Answer
First here it is declared the function remove duplicate with the list and itr as arguments. Here list is the integer list and the itr is iterator variable which checks the list for duplicates.
Then in the 2 statement checking that itr is having the value which is equal to the last element in the list or when the itr is incremented by 1 which means it comes to the next element in the list when it is incremented if it is the last element in the list then
It returns the current list.
Else if not the last element of the list the current value is stored in itr and when the itr increments if the current value in the itr is equal to the next element in the list then it removes that element from the list.
Then it returns the new list.