c - C 中的段错误编译器错误

标签 c linked-list

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/

相关文章:

c - 在 C 中,我想以某种方式从文件中逐行读取文件的末尾长度发生变化

java - 在java中打印链表

java - 在链表中查找大写字母并返回包含找到的元素的新链表?

c - while(true) 之前的 printf 消失

结合陀螺仪和加速度计数据

我们可以将字母数字值存储为 int 数据类型吗

java - regexec 未返回所有预期的匹配项

C++ 函数返回链表

c - 链表搜索功能

c - 如何在 C 中使用枚举