2014-12-13 145 views
0

我試過下面的代碼,我得到這個錯誤。我得到「未處理的異常的類型'System.NullReferenceException'發生」如何解決它?

Linkedlist.exe中發生未處理的類型爲'System.NullReferenceException'的異常其他信息:未將對象引用設置爲對象的實例。

我認爲問題出在insertlast(),當我檢查類似問題的解決方案時,他們討論了實例化新節點。我的方法,即節點* 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

您應該使頭爲空。接下來,在將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-> next之間的區別。 – 2014-12-13 07:03:54

+1

在while循環結束後的上述問題中,**節點p **指向最後一個元素,並且** p-> next **指向null。因此,您應該將**節點q **(其中包含要添加的當前值)分配給** p-> next **。如果你這樣做** q = p-> next ** u將最終爲**節點q **分配null,並且您的原始列表** head **保持不變。 – 2014-12-13 07:11:30

相關問題