[英]Remove a node in LinkedList in Java given the node reference
例如,如果我有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)...
如果我自己實施雙向鏈表,
currentNode.prev.next = currentNode.next;
currentNode.next.prev = currentNode.prev;
Java的LinkedList實現是否支持此操作?
我相信這只是一個復制粘貼錯誤,您忘記將節點x添加到鏈接列表中。 假設您的正確代碼是這樣的:
Integer x = new Integer(10);
ll.add(x);
ll.add(4);
您可以使用remove(Object o)
方法從java LinkedList中刪除一個節點。 因此,調用它以從鏈表ll
刪除節點x
。
ll.remove(x); //removes x from linkedlist but does not delete object x
它將x
從鏈表中刪除,但是對象x
在代碼中仍然有效並且可以在其他任何地方使用。
看看javadoc 。
對於java.util.LinkedList<E>
public E remove(int index)
刪除此列表中指定位置的元素。 將所有后續元素向左移動(從其索引中減去一個)。 返回從列表中刪除的元素。
還有一個remove(Object x)
可以執行相同的操作,但是是針對特定對象而不是索引。
那是您要找的東西嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.