PDA

View Full Version : LinkedList help


unc123w
09-29-2008, 01:57 AM
I'm working on a Linked List class and need a "removeAll" method that will iterate through a list remove each instance of x, then return a new list with these objects remove.

public void removeAll(T x) {

java.util.Iterator<T> it = this.iterator();
while(it.hasNext()) {
LinkedList l = new LinkedList();
T object = x;
l.remove(x);
System.out.println(it.next());
System.out.println(l);


}

}

In the main method, I've got this to add numbers to the list then remove each instance of 3.

ExtendedLinkedList<Integer> list3 = new ExtendedLinkedList<Integer>();
list3.add(3);
list3.add(4);
list3.add(6);
list3.add(3);
list3.add(9);
list3.removeAll(3);

I feel like I'm close, but the output I'm getting is the actual list, and an empty list. :p



3
[]
4
[]
6
[]
3
[]
9
[]

shadowmaniac
09-29-2008, 02:47 AM
public void removeAll(T x) {
java.util.Iterator<T> it = this.iterator();
while(it.hasNext()) {
LinkedList l = new LinkedList(); // list is empty and not initialized
T object = x;
l.remove(x);
System.out.println(it.next());
System.out.println(l);
}
}
The reason you're getting an empty list as output is because every time you go to the while loop, you create an empty list "l". You want to create the actual list outside the loop and then initialize it to the values of list3. Basically something like this:

public void removeAll(T x) {
java.util.Iterator<T> it = this.iterator();
LinkedList l = new LinkedList();
l.addAll(<<<<reference to list3>>>>) //initialize l
while(it.hasNext()) {
T object = x;
l.remove(x);
System.out.println(it.next());
System.out.println(l);
}
}
Don't hold me up on the validity of the above code though. Still, my "observations" should be good.