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;
}
現在有用了,謝謝。我想知道p-> next = q和q = p-> next之間的區別。 – 2014-12-13 07:03:54
在while循環結束後的上述問題中,**節點p **指向最後一個元素,並且** p-> next **指向null。因此,您應該將**節點q **(其中包含要添加的當前值)分配給** p-> next **。如果你這樣做** q = p-> next ** u將最終爲**節點q **分配null,並且您的原始列表** head **保持不變。 – 2014-12-13 07:11:30