Node* Insert(Node *head,int data)
{
// Complete this method
Node *temp, *temp1;
temp1 = head;
temp = (Node *)malloc(sizeof(Node));
temp->data = data;
temp->next = NULL;
while(temp1->next!=NULL){
temp1 = temp1->next;
}
temp1->next = temp;
return head;
}
我正在尝试编写简单的代码来插入到数组的末尾。该方法适用于 GCC 编译器,但使用 HackerRank 上的在线编译器进行编译时会出现段错误错误。对于不同的编译器,程序的工作方式是否不同?
最佳答案
根据我的评论:第一种情况,当链表为空时,head 将为 NULL。因此添加一个条件,如果 head 为 null,则将 temp 分配给 head
Node* Insert(Node *head,int data)
{
// Complete this method
Node *temp, *temp1;
temp1 = head;
temp = (Node *)malloc(sizeof(Node));
temp->data = data;
temp->next = NULL;
if(head==NULL) head=temp; //ADDED THIS LINE
else{
while(temp1->next!=NULL){
temp1 = temp1->next;
}
temp1->next = temp;
}
return head;
}
关于c - C 中的段错误编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48789651/