I have a doubt my circular list program inserts the first node but when inserting another I get an error I could help improve it

0

Method to insert a node in a list gives me error when inserting another node

Here is the code where I have problems:

public void insertar(int dato)
 {
  if(cabecera == null)
  {
   cabecera = new Nodo(dato);
  }
  else{

   cabecera.setant(new Nodo(cabecera.getant(),dato,cabecera)); 
   cabecera.getant().getant().setsig(cabecera.getant());
  }
 }
    
asked by Misael 26.10.2016 в 06:13
source

1 answer

1

header.getant (). getant () returns NullPointerException because the first getant () returns you null.

public void insertar(int dato) {
    if (this.cabecera == null) {
        this.cabecera = new Nodo(dato);
        this.fin = this.cabecera;
    } else {
        Nodo nuevoNodo = new Nodo(dato);
        nuevoNodo.setSig(this.cabecera);
        this.fin.setSig(nuevoNodo);
        this.fin = nuevoNodo;
    }
}

I suggest that in your circular list class you keep a pointer that allows you to save which was the last node added. This helps you improve insertion times.

    
answered by 26.10.2016 в 09:02