Remove a node in LinkedList in Java given the node reference

六眼飞鱼酱① 提交于 2019-12-12 01:11:58

问题


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?


回答1:


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.




回答2:


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?



来源:https://stackoverflow.com/questions/19920715/remove-a-node-in-linkedlist-in-java-given-the-node-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!