S.Dan
S.Dan

Reputation: 1930

I get "unhandled exception of type 'System.NullReferenceException' occurred" how to solve it?

I tried the following code and I get this error.

An unhandled exception of type 'System.NullReferenceException' occurred in Linkedlist.exe Additional information: Object reference not set to an instance of an object.

I think the problem is in insertlast() and when I checked the solutions to similar problems, they talk about instantiating the new node. I my method i.e. Node *q = new Node; wrong?

struct Node {
    int data;
    Node* next;
};
int is_list_empty(struct Node*head){
    int count=0;
    Node* p = head; 
    while (p!= NULL) 
{ 
  ++count; 
  p = p->next; 
  cout<<"go";
}
    return count;
}

void insertlast(struct Node *head,int value)
{
    Node *q = new Node;
    q->data=value;
    q->next=NULL;
    Node *p=head;
    while(p!=NULL)
    {
        p=p->next;
    }
    q=p->next;
}

void display(struct Node *head){
    Node*p = head;
    while(p!=NULL){
        cout <<p->data<< "  ";
        p=p->next;
    }
}

int main(){
    //Node *head = NULL; 
    Node *head;
    Node *x ;             
    x = (Node*)malloc(sizeof(Node));
    x->data=112;
    x->next = head;
    head = x;
    display(head);  
    //works fine upto here and 112 is displayed
    insertlast(head,34);
    insertlast(head,32);
    insertlast(head,44);
    display(head);
    cout<< is_list_empty(head);
    system("Pause");
    return 0;
}

Upvotes: 0

Views: 1748

Answers (1)

Sanjeev Hegde
Sanjeev Hegde

Reputation: 168

You should make head null . Next there is mistake in assigning q back to p (It should be p->next=q ) and your while loop should check only up to p->next!=NULL.
See the changes i have made.

struct Node {
    int data;
    Node* next;
};
int is_list_empty(struct Node*head){
    int count=0;
    Node* p = head; 
    while (p!= NULL) 
{ 
  ++count; 
  p = p->next; 
  cout<<"go";
}
    return count;
}

void insertlast(struct Node *head,int value)
{
    Node *q = new Node;
    q->data=value;
    q->next=NULL;
    Node *p=head;
    while(p->next!=NULL)
    {
        p=p->next;
    }
   p->next=q;
}

void display(struct Node *head){
    Node*p = head;
    while(p!=NULL){
        cout <<p->data<< "  ";
        p=p->next;
    }
}

int main(){
    //Node *head = NULL; 
    Node *head=NULL;
    Node *x ;             
    x = (Node*)malloc(sizeof(Node));
    x->data=112;
    x->next = head;
    head = x;
    display(head);  
    //works fine upto here and 112 is displayed
    insertlast(head,34);
    insertlast(head,32);
    insertlast(head,44);
    display(head);
    cout<< is_list_empty(head);
    system("Pause");
    return 0;
}

Upvotes: 1

Related Questions