如何删除链表中的第一个节点?

时间:2013-02-06 21:27:46

标签: java linked-list

我知道这是一个愚蠢的问题,但是我很难删除链表中的第一个节点,即使算法在第一个节点不是第一个节点时也能正常工作。

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是另一个包含大量数据的课程,我不认为它会在这里有用。

2 个答案:

答案 0 :(得分: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

你可能还需要重新分配尾巴。

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

答案 1 :(得分:0)

解决了!

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

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