Java 使用带参数的方法删除对象表单列表

Java 使用带参数的方法删除对象表单列表,java,generic-list,Java,Generic List,我正在尝试使用一种方法从列表中删除一个对象,该方法具有我希望删除的特定索引。这里比较棘手的部分是,这个列表是一个双链接列表,当我从中删除一个节点时,需要将下一个和上一个指针重定向到正确的节点。 这里是我到目前为止得到的,但代码似乎没有正确重定向指针,我会通知任何输入 private static final class Node<T> { private T value; private Node<T> previous, next;

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

 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;

  }
私有静态最终类节点
{
私人T值;
私有节点上一个,下一个;
私有节点(T值、上一个节点、下一个节点)//构造函数
{
这个值=值;
this.previous=先前;
this.next=next;
}
}
专用节点头;//第一名
专用节点名称;//最后一名
公共T删除(int索引){
indexcontrol(index);//检查索引是否合法
节点q,p=null;
如果(索引==0)
{
q=头;
head=head.next;
}
其他的
{
p=findNode(index-1);//查找位置索引上的节点值
q=p.next;
p、 next=q.next;
}
如果(q==tale)tale=p;
T值=q值;
q、 值=空;
q、 next=null;
返回值;
}

您可以看到的源代码,然后您将知道如何实现它。

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

prevNode.next = origNode.next;
nextNode.prev = origNode.prev;

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

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;
    }
}
public T删除(int索引){
如果(索引==0){
//拆下头部
}else if(索引==大小){
//脱尾
}
否则{
节点p=null;
节点q=null;
节点r=null;
p=findNode(index-1);//查找需要删除的节点之前的节点
q=p.next;//q是要删除的节点
r=q.next;//r是要删除的节点旁边的节点
p、 next=r;
r、 先前=p;
//您可以显式删除该节点,但GC仍将收集该节点。
q、 next=null;
q、 previous=null;
T值=q值;
q、 值=空;
返回值;
}
}

如果您删除元素,为什么不让您的方法
无效
?我在另一种方法中使用返回值感谢所有的答案,现在就有意义了!