Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2

Thread: LinkedList help

  1. #1
    New to the CF scene
    Join Date
    Sep 2008
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    LinkedList help

    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.

    Code:
    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.

    Code:
    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.



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

  • #2
    Regular Coder
    Join Date
    Apr 2005
    Location
    Ohio
    Posts
    254
    Thanks
    1
    Thanked 63 Times in 63 Posts
    Quote Originally Posted by unc123w View Post
    Code:
    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:

    Code:
    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.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •