Parker
Parker

Reputation: 3

Removes elements at even indices

The removeElementsAtEvenIndices() Method should remove objects at even indices within the LinkedList. For instance, if the LinkedList contains { Apple, Banana, Melon, Orange }, then after calling this method, the LinkedList should contain { Banana, Orange } since Applet at the index 0 and Melon at the index 2 need to be removed. Each element within the LinkedList can be labeled starting the index 0, and based on this assumption, elements should be removed. If the LinkedList does not contain any element, then the method should not change its content.

I currently have this code, but it will only remove the odd indicies.

 public void removeElementsAtEvenIndices()
 {
     ListIterator iterator = listIterator();
     while(iterator.hasNext())
     {
        iterator.next();
        if(iterator.hasNext())
        {
           iterator.next();
           iterator.remove();
        }
     }

}

Upvotes: 0

Views: 74

Answers (3)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79175

You can correct the problem as well as make your code simpler to understand by using a counter as follows:

public void removeElementsAtEvenIndices() {
    int counter = 0;
    ListIterator iterator = listIterator();
    while (iterator.hasNext()) {
        iterator.next();
        if (counter % 2 == 0) {
            iterator.remove();
        }
        counter++;
    }
}

Alternatively, you can solve it by promoting iterator.remove() one level up as follows:

public void removeElementsAtEvenIndices() {
    ListIterator iterator = listIterator();
    while (iterator.hasNext()) {
        iterator.next();
        iterator.remove();
        if (iterator.hasNext()) {
            iterator.next();
        }
    }
}

Upvotes: 1

RaffleBuffle
RaffleBuffle

Reputation: 5455

Keeping with your current approach you'd do this:

public void removeElementsAtEvenIndices()
{
    ListIterator iterator = listIterator();
    while (iterator.hasNext())
    {
        iterator.next();
        iterator.remove();      
        if (iterator.hasNext()) iterator.next();
    }
}

However, I would make the intent clearer:

public void removeElementsAtEvenIndices()
{
    ListIterator iterator = listIterator();
    for (int i=0; iterator.hasNext(); i++)
    {
        iterator.next();
        if ((i % 2) == 0) iterator.remove();
    }
}

or maybe this:

public void removeElementsAtEvenIndices()
{
    ListIterator iterator = listIterator();
    for (boolean even=true; iterator.hasNext(); even=!even)
    {
        iterator.next();
        if (even) iterator.remove();
    }
}

Upvotes: 1

cegredev
cegredev

Reputation: 1579

This should work:

public void removeElementsAtEvenIndices() {
    ListIterator iterator = listIterator();

    while(iterator.hasNext()) {
        iterator.remove();

        if(iterator.hasNext())
            iterator.next();
     }
}

Upvotes: 0

Related Questions