gpt4 book ai didi

c - 在单链表末尾插入一个元素

转载 作者:行者123 更新时间:2023-11-30 21:21:25 26 4
gpt4 key购买 nike

从早上起我就一直在尝试修复此代码,但可以完成。所以,最后我需要一些帮助来找出错误。代码编译时没有错误,但是当我从终端运行它时,我收到一条错误消息“段错误:11”

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


struct Node{
int data;
struct Node *next;
};


struct Node *head;


void Insert(int data);
void Print();


int main()
{
head = NULL; //list is empty

Insert(3);
Insert(5);
Insert(2);
Insert(8);

Print();

return 0;
}


void Insert(int data)
{
struct Node *temp = malloc(sizeof(struct Node));

temp->data = data;
temp->next = NULL;

struct Node *temp1 = head;

while(temp1 != NULL)
{
temp1= temp1->next;
}

temp1->next = temp;
}


void Print()
{
struct Node *temp =head;

while(temp != NULL)
{
temp = temp->next;
printf("%d", temp->data);
}
}

最佳答案

  1. 您绝不能将 head 设置为 NULL 以外的任何值。

  2. (即使您修复了上述问题)当您到达 temp1->next = temp; 时,temp1 也保证为 NULL .

附注我不认为将变量称为 temptemp1 等是一个很好的做法。从这些名称中不可能看出它们的功能是什么。

关于c - 在单链表末尾插入一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26193712/

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