所以我写了我自己的链表(和列表节点)在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