user13355505
user13355505

Reputation:

How to remove duplicates in a java LinkedList?

I'm attempting to remove duplicates from a premade sorted LinkedList and I'm not permitted to use hash sets, sets, maps, collections, nodes, arrays, indexes or etc, only loops and I'm a bit stumped. I've messed around with my code but I either have exceptions thrown or I remove everything. Any help is appreciated! This is my current code:

private void duplicates() {

    ListIterator<String> it = sorts.listIterator();
    it.next();
    while(it.hasNext()) {

        String last = it.previous();
        String nest = it.next();

        if(last.equals(nest)) {
            it.remove();
        }
    }
}

Upvotes: 1

Views: 548

Answers (3)

Nikolas
Nikolas

Reputation: 44466

...from a premade sorted LinkedList.

As long as you can guarantee the list is really sorted (not ordered, but truly sorted) which results in the duplicated elements are next to each other, you can simply compare these 2 neighbors and shift if they are different.

only loops

If you mean rather "iterations", than loops (for-each), then this is a way to go:

ListIterator<String> it = sortedCounties.listIterator();
String current = it.next();                          // get a first element
while (it.hasNext()) {
    String next = it.next();                         // get another one
    if (current.equals(next)) {                      // if equal
        it.remove();                                 // .. remove the "next" element
    } else {
        current = next;                              // .. or else shift by one
    }
}

Upvotes: 2

Lungu Daniel
Lungu Daniel

Reputation: 844

You could use Java 8 Stream API for this kind of job

private void unduplicate() {
  sortedCounties = sortedCounties.stream()
        .distinct()
        .collect(Collectors.toCollection(LinkedList::new));
}

Upvotes: 0

Sai Ashish Das
Sai Ashish Das

Reputation: 36

So the basic idea to remove duplicate elements is to select one and compare it with the rest of the elements if found duplicate then remove it.

sudo code:

currentElement = iterator1.next()
while iterator1.hasNext()
   while iterator2.hasNext()
      nextElement = iterator2.next()
      if currentElement == nextElement
         then remove nextElement
      else
         then nextElement = iterator2.next()
   currentElement = iterator1.next()

Upvotes: 0

Related Questions