Greetings to all, I premiere on this wonderful page with a block of code that continually skips "Segmentation fault" error and I do not know why.
The code must receive an integer, create a node with that integer and then insert it into the list maintaining an increasing order.
When it is the case that the node is added before the first term it works fine, but when I have to add it after the first one, I continually skip the error.
The code:
#include <iostream>
using namespace std;
class nodo{
private:
int edad;
nodo *siguiente;
public:
nodo (int N, nodo *sig=NULL){
edad=N;
siguiente=sig;
};
friend class lista;
};
class lista{
private:
nodo *primero;
nodo *actual;
public:
lista (){
primero=NULL;
actual=NULL;
}
bool listaVacia(){
return (primero==NULL);
}
void insertar(int N){
nodo *nuevo=new nodo(N);nodo *aux=primero; actual=primero;
bool k=0;
int i=0;
if (listaVacia()){
primero=nuevo;
}else{
while(actual || k==0){
if(actual->edad>N){
nuevo->siguiente=actual;
if (i==0) primero=nuevo;
k=1;
}else if (i==0){
actual=actual->siguiente;
}else{
actual=actual->siguiente;
aux=aux->siguiente;
}
i++;
}
if (k==0){
actual=aux;
actual->siguiente=nuevo;
}
}
}
void mostrar(){
nodo *tmp=primero;
while(tmp){
cout<<tmp->edad<<"--->";
tmp=tmp->siguiente;
}
cout<<"NULL"<<endl;
}
};
On the other hand, the main is that simple:
int main() {
lista newlista;
int A;
cout<<"Ingrese primera edad"<<endl;
cin>>A;
newlista.insertar(A);
newlista.mostrar();
cout<<"ingrese otra edad"<<endl;
cin>>A;
newlista.insertar(A);
newlista.mostrar();
}