我试图使用具有我希望删除的特定索引的方法从列表中删除对象。这里棘手的部分是这个列表是一个双链接列表,当我从中删除一个节点时,下一个和上一个指针需要重定向到正确的节点。这是我到目前为止得到的,但代码似乎没有正确重定向指针,我会接受任何输入!
private static final class Node<T>
{
private T value;
private Node<T> previous, next;
private Node(T value, Node<T> previous, Node<T> next) // constructor
{
this.value = value;
this.previous = previous;
this.next = next;
}
}
private Node<T> head; // first in the list
private Node<T> tale; // last in the list
public T remove(int index) {
indexcontrol(index); // checks if legal index
Node<T> q, p = null;
if(index == 0)
{
q = head;
head = head.next;
}
else
{
p = findNode(index-1); // finds the nodes value on place index
q = p.next;
p.next= q.next;
}
if ( q== tale) tale = p;
T value = q.value;
q.value = null;
q.next = null;
return value;
}
您需要将上一个和下一个指针分配给正确的节点。
public T remove (int index){
if (index==0){
//remove head
}else if (index == size){
//remove tail
}
else {
Node<T> p = null;
Node<T> q = null;
Node<T> r = null;
p = findNode(index-1); // finds the nodes previous to the node that needs to be removed
q = p.next; //q is the node you want to remove
r = q.next; //r is the node next to the node you want to remove
p.next = r;
r.previous = p;
//you can explicitly delete the node, but GC will collect anyway.
q.next = null;
q.previous = null;
T value = q.value;
q.value = null;
return value;
}
}
你可以看到java.util.LinkedList的源代码,然后你就会知道如何实现它。
似乎在语句else
您只更改一个指针,而您应该更改其中两个指针。应该是这样的:
prevNode.next = origNode.next;
nextNode.prev = origNode.prev;