[英]How to delete the first node in a 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是另一個包含大量數據的類,我認為它不會在這里有用。
在鏈表中,您有一個指向第一個節點的指針和一個指向最后一個節點的指針。 您將在(偽代碼)中執行以下操作
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
您可能還需要重新分配尾部。
如果您發布鏈接列表類,我們可以為您提供進一步的幫助。
解決了!
if(aux.getInfo().getDni() == DNI)
{
Raiz=aux.getProx();
flag=true;
}
這就是我刪除列表中第一個節點的方式!感謝大家提出的問題/答案!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.