0

This is the code I have where I would like to remove the value by passing as a parameter from Linkedlist but it is removing the value by index instead of removing the value.

Below is the excerpt from code where I would to remove the value x and y from the linkedlist not the element by index.

for(int i=2; i < ls/2; i++)
    {
        int x = i*2;
        int y = i*i;
        if(x<ls)
            ll.remove(x);
        if(y<ls)
            ll.remove(y);
    }

This is the entire code for your understanding

import java.util.LinkedList;

public class LinkedListEx {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        LinkedList<Integer> ll = new LinkedList<Integer>();
        for(int i = 0; i< 10; i++)
        {
            ll.add(i);
        }
        System.out.println(ll);
    
        int ls = ll.size();
    
        for(int i=2; i < ls/2; i++)
        {
            int x = i*2;
            int y = i*i;
            if(x<ls)
                ll.remove(x);
            if(y<ls)
                ll.remove(y);
        }
    
        System.out.println(ll);
    }
}
Sreedhar Danturthi
  • 7,119
  • 19
  • 68
  • 111

1 Answers1

0

You can try using

ll.remove(new Integer(x))

which will call the remove function that waits an object, not and int and will do as asked. Or you can also use

ll.removeFirstOccurrence(x);