[英]Segmentation fault for insertion in linked list
class linkedList
{
public:
int data;
linkedList *next;
};
linkedList* createNode(int data)
{
linkedList *newNode;
newNode->data = data;
newNode->next =NULL;
return newNode;
}
linkedList* insertData(linkedList *r,int data)
{
if(r==NULL)
{
r=createNode(data);
return r;
}
else
{
linkedList *node;
node=createNode(data);
r->next=node;
return node;
}
}
int main()
{
linkedList *root=NULL;
root=insertData(root,10); // this line is giving segmentation fault
return 0;
}
You should allocate memory for new node into createNode function.您应该为新节点分配 memory 到 createNode function。 Like this: linkedList *newNode = new linkedList;
像这样:linkedList *newNode = new linkedList;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.