0

我知道这是一个愚蠢的问题,但我很难删除链表中的第一个节点,即使该算法在它不是第一个节点时有效。

public boolean eliminarInscripcion(int DNI)
{
    boolean flag=false;
    Nodo aux, aux2;        //Nodo=Node

    if(Raiz!=null) //If the list isn't empty
    {
        aux=Raiz;  //Raiz=Root
        if(aux.getInfo().getDni() == DNI)  //Is the first node the one i'm looking for?
        {
            aux.setProx(aux.getProx()); //Here is the main problem. (I've tried many things, this is one of them, looks silly anyway.)
            flag=true;
        }
        else
        {
            aux2=aux.getProx();  //getProx=getNext
            while(aux.getProx()!=null)
            {
                if (aux2.getInfo().getDni()==DNI)
                {
                    aux.setProx(aux2.getProx());
                    flag=true;
                    break;
                }
                else
                {
                    aux=aux.getProx();
                    aux2=aux2.getProx();
                }
            }
        } 
    }
    return flag;   
}

哦,非常感谢!

编辑:我将添加更多信息:List 类只有 1 个属性,即 Nodo (Raiz),nodo 类是这个:

public class Nodo
{
private Inscripcion Info;
private Nodo Prox;

public Nodo()
{
    Info = null;
    Prox = null;
}

public Nodo(Inscripcion info, Nodo prox)
{
    this.Info = new Inscripcion(info);
    this.Prox = prox;
}

public Inscripcion getInfo() 
{
    return Info;
}

public void setInfo(Inscripcion I) 
{
    this.Info = new Inscripcion(I);
}

public Nodo getProx() 
{
    return Prox;
}

public void setProx(Nodo P) 
{
    this.Prox = P;
}

@Override
public String toString()
{
    return Info.toString();
}

}

Inscripcion 是另一个具有大量数据的类,我认为它在这里不会有用。

4

2 回答 2

2

在链表中,您有一个指向第一个节点的指针和一个指向最后一个节点的指针。您将在(伪代码)中执行以下操作

LinkedList list = myList
Node node = list.head // get head
list.head = node.next // set new head to the second node in the list
node.next = null // remove the reference to the next node from the old head

您可能还必须重新分配尾部。

如果您发布您的链表类,我们可以进一步帮助您。

于 2013-02-06T21:32:38.577 回答
0

解决了!

if(aux.getInfo().getDni() == DNI)
        {
            Raiz=aux.getProx();
            flag=true;
        }

这就是我删除列表中第一个节点的方式!感谢大家的提问/回答!

于 2013-02-07T19:00:56.177 回答