2013-02-06 41 views
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是另一個擁有大量數據的課程,我認爲它不會在這裏有用。

+0

'Nodo'類是如何實現的? –

+0

發生了什麼,你不期待?它是不是刪除?拋出一個錯誤? – thegrinner

+0

'aux.setProx(aux.getProx());'看起來像一個沒有操作。我看不到'getProx'的定義,但是你不是指'aux.setProx(aux.getProx()。getProx());'? –

回答

0

解決了!

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

這就是我如何刪除第一個節點在我的名單!謝謝大家的提問/回答!

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 

您可能還需要重新分配尾部。

如果您發佈鏈接列表類,我們可以幫助您進一步。

+0

重置'node.next'的目的是什麼?我從來沒有做過,我還活着。 –

+0

您可能會保留對該節點的引用,但不會引用該引用的節點,在這種情況下,它不會被GC化。邊緣情況真的。 –

+0

IOW不是真的值得':-)'? –