c - 在C中实现链表时出现段错误

标签 c linked-list

我正在尝试创建一个简单的链表并在链表末尾插入一个节点。我遇到了段错误。

#include <stdio.h>
#include <stdlib.h>

struct node{
    int data;
    struct node *link;
};

void create(struct node *head){
    struct node* second = NULL;
    struct node* last = NULL;

    second = (struct node*)malloc(sizeof(struct node));
    last = (struct node*)malloc(sizeof(struct node));

    second -> data = 2;
    last -> data = 3;

    head -> link = second;
    second -> link = last;
    last -> link = NULL;
}

void insert_ending(struct node *head){
    struct node* temp = NULL;
    struct node* temp1 = NULL;

    temp1 = (struct node*)malloc(sizeof(struct node));
    temp1 -> data = 5;
    temp1 -> link = NULL;

    temp = head;
    while(temp != NULL){
       temp = temp -> link;
    }temp -> link = temp1;
}

void PrintList(struct node *head){
    while( head != NULL ){
        printf(" %d -->", head -> data);
        head = head -> link;
    }
    printf("\n");
}

int main(){
    struct node* head = NULL;
    head = (struct node*)malloc(sizeof(struct node));
    head -> data = 1;
    head -> link = NULL;

    create(head);
    PrintList(head);

    insert_ending(head);
    PrintList(head);
    return 0;
}

我遇到了段错误。输出结果如下。

1 --> 2 --> 3 --> Segmentation fault (core dumped)

最佳答案

在您的插入功能中,您需要更改为:

 temp = head;
    while(temp -> link != NULL){
       temp = temp -> link;
    }
    temp -> link = temp1;

原因是当你用 while 循环直到 temp == null 时,你不能之后做:temp -> link 因为 temp 已经是 null。

关于c - 在C中实现链表时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30286947/

相关文章:

c - 如何正确计算 C 中的 æ ø å(Unicode 作为 UTF-8)字符?

c++ - 是否可以在定义函数的位置之外声明函数的属性? (海湾合作委员会)

c - 检查文件中最常见的字母时如何忽略 ctrl+z(不区分大小写)

c - 为什么作者在这个链表插入操作中要使用双指针呢?

data-structures - 链表和队列有什么区别?

java - 如何在 Java 中打印变量的地址

java - 插入已排序的链表 - Java

C 位移位

c - 将结构插入链表不会显示为正确的节点

python - PyTypeObject 的静态工厂