# need help with removing repetitions from linked list...

• 03-08-2010, 10:53 PM
OptimusPrime
need help with removing repetitions from linked list...
so... i have a linked list, i need to delete all repetitions from the list.
i started working on it and i have 3 loops already... it turned out to be a real mess.
i wanted to treat it like arrays but it so much different when moving with pointers on a linked list.
the general idea is to take the first element and every time i find the same data on the list i delete it. by deleting i mean skipping this element.
can anyone help me with this one?
thanks,
OP
• 03-08-2010, 11:42 PM
FON
Optimus why don't you use Set - A collection that contains no duplicate elements. If you can create that collection at start like that - then there are no problems later.

If you are iterating through collection and removing elements at the same time - take care - use an Iterator.

Or maybe convert list to set like:

Code:

```List<String> myList = new ArrayList<String>();                     myList.add("A");                     myList.add("B");                     myList.add("A"); //duplicate                     myList.add("D");                     Set<String> mySet = new HashSet<String>(myList);                     for (Object theFruit : mySet)                       System.out.println(theFruit); //no duplicate                   }```
choosing right collection :

Java Practices -> Choosing the right Collection

hope you will solve it easily! cheers!
• 03-09-2010, 01:15 AM
OptimusPrime
hello,
2nd, i never wrote it, but its an assignment i have to do. its kinda complicated and i really want to figure out how to do it.
so switching to a set is not an option right now...

any other ideas?
thanks...
• 03-09-2010, 07:01 PM
OptimusPrime
help anyone?
• 03-09-2010, 07:31 PM
m00nchile
You did describe the algorithm very well, now, are you supposed to use the already implemented LinkedList, or make your own representation of the structure? You description contains all the steps you need to do, so it shouldn't be too difficult to translate it into code.
• 03-09-2010, 08:17 PM
OptimusPrime
i already have the linked list. i need to work on it.
i know i have all the steps im just messing up the pointers...
really, i cant make it work.
• 03-09-2010, 08:20 PM
PhHein
What have you tried? Which code failed?
• 03-09-2010, 09:22 PM
OptimusPrime
im stuck inside the 2nd loop.
i dont know how to connect between the pointers after i find 2 that identical...
• 03-09-2010, 09:29 PM
JosAH
Quote:

Originally Posted by OptimusPrime
i started working on it and i have 3 loops already... it turned out to be a real mess.

If you don't want to use FON's suggestion then two loops are enough: 1) to walk over all elements of the list and 2) another one to remove the duplicates pointed to by 1)

kind regards,

Jos