2014-12-13 1 views
0

다음 코드를 시도했지만이 오류가 발생합니다."처리되지 않은 예외 'System.NullReferenceException'이 발생했습니다"해결 방법?

처리되지 않은 'System.NullReferenceException'형식의 예외가 Linkedlist.exe에서 발생했습니다. 추가 정보 : 개체 참조가 개체 인스턴스로 설정되지 않았습니다.

나는 문제가 insertlast()에 있다고 생각하고 비슷한 문제에 대한 해결책을 찾았을 때 새로운 노드를 인스턴스화하는 것에 대해 이야기합니다. I 내 방법, 즉 노드 * q = 새 노드; 잘못 되었나요?

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; 
} 

답변

1

머리를 null로 지정해야합니다. 다음으로 q를 p (이어야합니다.p->next=q이어야합니다)에 할당하는 실수가 있으며 while 루프는 p->next!=NULL까지만 확인해야합니다.
내가 변경 한 사항을 확인하십시오.

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; 
} 
+0

감사합니다. 나는 p-> next = q와 q = p-> 다음의 차이점을 알고 싶다. –

+1

위의 문제에서 while 루프가 끝난 후 ** 노드 p **는 마지막 요소를 가리키고 ** p-> next **는 null을 가리 킵니다. 따라서 ** p-> 다음에 ** 노드 q ** (추가 할 현재 값을 포함)를 할당해야합니다. u가 ** q = p-> 다음에 ** u는 ** node q **에 null을 할당하게되고 원래 목록 ** head **는 변경되지 않습니다. –