[Solved] Method to build a new Linked List with the odd numbered elements from a given Linked List [closed]


I’m not really a Java developer but this should work better:

import java.util.*;

public class ExtLinkedList<E> extends LinkedList<E>
{

    public ExtLinkedList<E> oddItemsList () 
    {
        ExtLinkedList<E> oddList = new ExtLinkedList<E>();

        //Get the iterator of the current list instead of the new empty list.
        //Otherwise you will iterate over nothing.
        ListIterator<E> itr = listIterator();

        for(int i = 0; itr.hasNext(); i++)
        {
            E element = itr.next();
            if(i % 2 == 1)
            {
                //System.out.print(element);
                oddList.add(element);
            }
        }
        return oddList;
    }
}

Modifications:

  1. Call listIterator() on the current list instead of on the empty oddList.
  2. You don’t need to remove the elements as you go because this would alter your original list.
  3. Add the element returned by next() to your oddList

1

solved Method to build a new Linked List with the odd numbered elements from a given Linked List [closed]