Ordered linked list

Hi, I'm trying to make an ordered linked list; I've completed the code and in the compiling there are no error or warning but the program crash after the first insert in the list
here the code:

MAIN.CPP

#include <iostream>
#include <stddef.h>
#include "Lista.h"

using namespace std;

int main() {
char n;
Lista l;
while(n!='e'){
cout<<"Premi 'i' per inserire un elemento,'s' per stampare la lista, 'e' per uscire"<<endl;
cin>>n;
if(n=='i')
l.insert();
if(n=='s')
l.stampa();
}
return 0;
}

LISTA.H
#ifndef LISTA_H_
#define LISTA_H_
#include <stddef.h>
namespace std{
class Lista{
private:
struct nodo{
nodo *next ; /* puntatore nodo successivo */
int num ; /* Dati contenuti nel nodo */
};
public:
nodo *testa;
nodo *temp;

Lista(){
testa = NULL;
temp = NULL;
}
void insert();
void stampa();
};
}
#endif /* LISTA_H_ */

LISTA.CPP
#include "Lista.h"
#include <iostream>
using namespace std;

void Lista::insert(){
int inserimento;
cout<<"inserisci elemento"<<"\n";
cin>>inserimento;
if(testa==NULL){
testa->num = inserimento;
}
else{
temp = testa;
while(temp->num < inserimento) //inserimento in mezzo
{
temp = temp->next;
if(temp->num > inserimento){
temp->next->num = temp->num;
temp->num = inserimento;
}
}
}
}

void Lista::stampa(){
temp = testa;
while(temp!=NULL){
cout<<temp->num<<endl;
temp = temp->next;
}
}

thanks in advance
Last edited on
morning.

1
2
3
if(testa==NULL){
 testa->num = inserimento;
 }


I think you actually need to 'new up' a testa object here. you're trying to use a null pointer here, which is bad.
Thanks you but how Can I do it? Can you make me a code example?
There are lots of sites, for example:
http://www.programming-techniques.com/2011/11/linked-list-implementation-in-c.html

but if you don't understand why you have to do this I'd advise re-learning pointers and dynamic memory allocation in C.
Topic archived. No new replies allowed.