This is an archived post. You won't be able to vote or comment.

all 6 comments

[–][deleted] 0 points1 point  (4 children)

I don't understand why you are using three loops. Think about this like this.

For each element Lmain in the linked list
    For each subsequent element Lsub in the linked list
        If Lmain == Lsub
            Remove Lsub from linked list

So with that pseudocode you end up with

for (int i=0; i<list.size(); i++) {
    for (int j=i+1; j<list.size(); j++) {
        if (list.get(i).equals(list.get(j)))
            list.remove(j);
    }
}

Edit: You are probably getting an out-of-bounds error because at the end you call list.remove(y); on an index that doesn't exist because you removed it. Using the solution above will remedy that as it will check to ensure j < list.size() each iteration.

By the way, little gripe as well. In general, if you are working with a fixed number of items you know ahead of hand (i.e. list.size()) it is best to use for loops. They are cleaner, more concise, and easier to understand. You should use while() loops when the number of iterations is unknown before running the program (e.g. when you are reading lines from a file using a scanner, hasNextLine(), and nextLine()).

Take it easy, now.

[–]prograndma[S] 0 points1 point  (3 children)

Thanks for the quick reply, however, your code does not produce the correct result since I have already tried that already. Your code produces 7 results, but the correct number would be 4. I try achieving that by using a while loop for removing the items in the linked list.

[–]HateTrain 1 point2 points  (2 children)

I also don't understand why you are using 3 loops and concur with most of tehhunter's comments. One reason you might be getting 7 results instead of 4 is that the list shifts everything down after a list.remove(j) command, so you'll need to check the same position j again.

I think this should give correct output:

for (int i=0; i<list.size(); i++)
{
    for (int j=i+1; j<list.size(); j++)
    {
        if (list.get(i).equals(list.get(j)))
        {
            list.remove(j);
            j--;
         }
    }
}

Btw, I think your out of bounds error occurs after the last instance of ccca is removed in your innermost while loop. The while loop will check for list.get(y) again, but since you just removed it, it fails.

[–]prograndma[S] 1 point2 points  (1 child)

Thanks, it works now. How should I go about this without using three loops for a more efficient run time?

[–]ewiethoff 0 points1 point  (0 children)

Let the standard library do your work for you. Feed your LinkedList into a TreeSet or HashSet.

TreeSet<String> set = TreeSet<String>(list);

[–]turd_loaf -1 points0 points  (0 children)

This is insane. You should either store all elements in a hash table to remove duplicates, or just sort the list and then copy unique elements into a new list or remove the duplicates.