gpt4 book ai didi

c - C中的排序链表

转载 作者:太空宇宙 更新时间:2023-11-04 06:29:08 25 4
gpt4 key购买 nike

根据一些论坛和教程,我编写了一个排序链表的代码。该代码导致核心转储。我相信错误发生在第 50 行之后,我试图在末尾插入节点。你能帮我解决这个问题吗?我不确定我做错了什么。谢谢。

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

struct node
{
char val;
struct node* next;
};

struct node *start = (struct node*) NULL;

// definition of creating only first node
struct node* create(char* data)
{
struct node* temp;
temp = (struct node*)malloc(sizeof(struct node));
if (start == NULL)
{
temp->val = data;
temp->next = NULL;
start = temp;
}
printf("List created\n");
}

struct node* insert(char* data)
{
int i, pos;
struct node* tempnode, *ptr;
ptr = start;

while(ptr != NULL)
{
if (data <= ptr->val)
{
printf("!!!Inserting before!!!\n");
tempnode = (struct node*)malloc(sizeof(struct node));
tempnode->val = ptr->val;
tempnode->next=ptr->next;
ptr->val = data;
ptr->next=tempnode;
break;
}
else if (data > ptr->val)
{
printf("!!!Going next!!!\n");
ptr = ptr->next;
}
if (ptr == NULL) //insert behind the node
{
tempnode = (struct node*)malloc(sizeof(struct node));
tempnode->val = data;
tempnode->next = NULL;
ptr->next = tempnode;
printf("!!!Placed at the end!!!\n");
break;
}
}
}

void display()
{
struct node* ptr; // ptr is pointer
ptr = start;
while (ptr != NULL)
{
printf("%s->", ptr->val);
ptr = ptr->next;
}
printf("End of list\n");
}

int main()
{
char* data;
int i = 0;

create(0);
FILE* file = fopen("words.txt", "r");

while (i < 10)
{
fscanf(file, "%s", &data);
printf ("data is %s\n", &data);
insert(data);
i++;
}
display();

}

最佳答案

在这里,在您的insert 函数的底部,您已保证ptr 为NULL,但您还执行了ptr->next = ... 。这等同于 (*ptr).next = ...,它取消引用 NULL 指针!

if (ptr == NULL) //insert behind the node
{
tempnode = (struct node*)malloc(sizeof(struct node));
tempnode->val = data;
tempnode->next = NULL;
ptr->next = tempnode;
printf("!!!Placed at the end!!!\n");
break;
}

关于c - C中的排序链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22712449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com