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