Removing duplicates chars

I need to create a method that will so that it does not contain any duplicate characters from the linked list, if duplicates were entered. For example, ‘M’, ‘A’, ‘S’, ‘S’, ‘A’, ‘C’, ‘H’, ‘U’, ‘S’, ‘E’, ‘T’, ‘T’, ‘S’, then after calling the method the remaining characters would be ‘M’, ‘A’, ‘S’, ‘C’, ‘H’, ‘E’, ‘T’

This is what I have, I am just not sure how to finish it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
  void Bag::removeDuplicate()
{
	if (head == NULL) {
		head = NULL;
	}

	Node *rc = new Node(head->data);

	Node* current = head;
	while (current != NULL)
	{
		bool isUnique = true;

		//check if node exists in current rc or not
		Node* rc_current = rc;

			while (rc_current != NULL)
			{
				if (rc_current->data == current->data)
				{
					isUnique = false;
				}
				rc_current = rc_current->next;
			}

		if (isUnique)
		{
			//add to current->data to rc as new Node
			Node *rc_current = new Node(rc_current->data);

		}
		current = current->next;
	}
}
Try putting each element in a set (which doesn't allow duplicates). If you can't - because it's a duplicate - then remove that element.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <list>
#include <set>
#include <algorithm>
using namespace std;

//================================================

template <typename T> void removeDuplicates( list<T> &L )
{
   set<T> S;
   L.erase( remove_if( L.begin(), L.end(), [&S]( T val ){ return !S.insert( val ).second; } ), L.end() );
}

//================================================

template <typename T> ostream & operator << ( ostream &strm, list<T> L ) { for ( auto e : L ) cout << e << " "; return strm; }

//================================================

int main()
{
   list<char> L = { 'M', 'A', 'S', 'S', 'A', 'C', 'H', 'U', 'S', 'E', 'T', 'T', 'S' };
   cout << "Before: " << L << endl;

   removeDuplicates( L );

   cout << "After:  " << L << endl;
}


Before: M A S S A C H U S E T T S 
After:  M A S C H U E T 


You seem to have lost a 'U' BTW.
Last edited on
Just out of curiosity, is there a way to write it without using a template?
Remove "template <typename T>" and replace "T" with the specific type you want.
Topic archived. No new replies allowed.