0

我试图使用具有我希望删除的特定索引的方法从列表中删除对象。这里棘手的部分是这个列表是一个双链表,当我从中删除一个节点时,需要将下一个和上一个指针重定向到正确的节点。这是我到目前为止所得到的,但代码似乎没有正确重定向指针,我会应用任何输入!

 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;

  }
4

3 回答 3

0

你可以看看java.util.LinkedList的源代码,然后你就会知道如何实现它。

于 2013-10-19T15:38:14.170 回答
0

似乎在else声明中您只更改了一个指针,而您应该更改其中的两个。应该是这样的:

prevNode.next = origNode.next;
nextNode.prev = origNode.prev;
于 2013-10-19T15:40:51.437 回答
0

您需要将上一个和下一个指针分配给正确的节点。

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;
    }
}
于 2013-10-19T15:51:11.930 回答