Reputation: 7081
For example, if I have LinkedList
LinkedList<Integer> ll = new LinkedList<Integer>();
ll.add(1);
ll.add(2);
ll.add(3);
Integer x = new Integer(10);
ll.add(x);
ll.add(4);
// now the list looks like 1->2->3->10->4
// what if I want to remove 10 and I still have the reference to that node x
// what is the API of that
// somethings like ll.remove(x)...
If I implement a doubly linked list by myself, just
currentNode.prev.next = currentNode.next;
currentNode.next.prev = currentNode.prev;
Does Java's implementation of LinkedList support this operation?
Upvotes: 0
Views: 3963
Reputation: 68715
I believe its just a copy paste error that you forgot to add the node x to your linked list. Assuming your correct code is like this:
Integer x = new Integer(10);
ll.add(x);
ll.add(4);
You can remove a node from java LinkedList using remove(Object o)
method. So call that to remove node x
from linkedlist ll
.
ll.remove(x); //removes x from linkedlist but does not delete object x
It will remove x
from the linkedlist but object x
is still alive in your code and usable anywhere else.
Upvotes: 3
Reputation: 1266
Take a look at the javadoc.
For java.util.LinkedList<E>
public E remove(int index)
Removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices). Returns the element that was removed from the list.
there's also a remove(Object x)
that does the same but for a specific object, not an index.
Is that what you were looking for?
Upvotes: 3