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?

5
  • 3
    You never added x to your list. Commented Nov 12, 2013 at 4:12
  • 2
    your linked list would be 1->2->3->4 because you never add 10 to it Commented Nov 12, 2013 at 4:12
  • What do you mean by "I still have the reference to that node x" ? Do you mean after deleting 'x' you still need a reference to 'x' or you mean you just have a reference to 'x' and you wish to delete that Commented Nov 12, 2013 at 4:14
  • Sorry, I forgot to add x, edited again Commented Nov 12, 2013 at 5:01
  • Possible duplicate of Pointer into Java LinkedList Node Commented Feb 20, 2018 at 11:42

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.