所以我寫了我自己的鏈表(和列表節點)在Java中作爲作業的一部分。如何從Java中的鏈接列表中刪除?
現在,我試圖擦除條目,但該功能不起作用。
我知道這個概念:
- 搜索節點保持先前的;
- 告訴上一個節點指向下一個節點;
- 返回或停止使用該節點,以便GC將其擦除。
由於某種原因,它不起作用。我可以一遍又一遍地刪除具有相同值的節點。恐怕這是與Java指針有關的東西。
代碼:
節點:
public class SimpleNode<E> {
private E value;
private SimpleNode<E> next;
public SimpleNode() {
this.value = null;
this.next = null;
}
public NoSimples(E data, SimpleNode<E> ref) {
this.value = data;
this.next = ref;
}
// Getters and Setters
}
列表:
public class LinkedList<E> implements Iterable<SimpleNode<E>> {
private SimpleNode<E> head;
private int size = 0;
public LinkedList() {
this.head = new SimpleNode<E>();
}
public void add(SimpleNode<E> node) {
this.addFirst(node.getValue());
}
public void addFirst(E item) {
SimpleNode<E> nonde = new SimpleNode<E>(item, this.head);
this.head = node;
size++;
}
public void add(E value) {
this.addFirst(value);
}
public SimpleNode<E> removeFirst() {
SimpleNode<E> node = this.head;
if (node == null) {
return null;
} else {
this.head = node.getNext();
node.setNext(null);
this.size--;
return node;
}
}
public SimpleNodes<E> remove(E value) {
SimpleNode<E> nodeAnt = this.head;
SimpleNode<E> node = this.head.getNext();
while (node != null) {
if (node.getValue()!= null && node.getValue().equals(value)) {
nodeAnt.setNext(node.getNext());
node.setNext(null);
return node;
}
nodeAnt = node;
node = node.getNext();
}
return null;
}
// Other irrelevant methods.
}
在Java中的概念是,如果一個對象沒有更多的引用,那麼GC將最終清理它。在你的情況下,你需要的只是從你的LinkedList中刪除對象,就是這樣。要從LinkedList中刪除,只需遍歷整個過程,然後從Iterator調用.remove()。 –
是的,但我試圖在上面的代碼中做到這一點,但它不起作用。 –
看來你正在跳過刪除的第一個節點:'nodeAnt = this.head'。這意味着在你看到它之前,第一個節點已經是「前面」了。 – fileyfood500