0

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?

Alfred Zhong
  • 5,853
  • 9
  • 39
  • 55

2 Answers2

3

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.

Juned Ahsan
  • 63,914
  • 9
  • 87
  • 123
  • Thank you so much! That is exactly what I am looking for! – Alfred Zhong Nov 12 '13 at 05:00
  • 1
    Note that this is an O(n) operation. `java.util.LinkedList` does not expose its internal nodes, so the only way to remove an element in constant time is while iterating over the list. This makes LinkedList#removeIf trivially O(n), but provides no benefit over ArrayList when removing a single element. – MikeFHay Feb 20 '18 at 11:41
3

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?

jgriego
  • 1,207
  • 7
  • 8