gpt4 book ai didi

c - 将节点插入到 LinkedList 中的最后一个位置

转载 作者:行者123 更新时间:2023-11-30 17:22:09 24 4
gpt4 key购买 nike

我需要将一个节点插入到链表的最后一个位置。这就是我想到的:

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

struct node { float data;
struct node * next;
};

struct node* makenode(float item){
struct node* p=(struct node*)malloc(sizeof (struct node));
if(p) p->data = item;
return p;
}
void init (struct node **p){
*p=0;
}
int addlast(struct node **ptr, float item){
struct node* p=makenode(item);
if(!p) return 0;
struct node* temp=*ptr;
while(temp->next)temp = temp->next;
p->next=0;
temp->next=p;
return 1;
}
float delfirst(struct node **ptr){
struct node* p =*ptr;
*ptr=(*ptr)->next;
float temp=p->data;
free(p);
return temp;
}

void main(){
struct node *list,*list2;
init (&list);
int i;

for(i=0;i<10;i++)addlast(&list,i);

while(list)printf("%4.2f\t",delfirst(&list));
getchar();

}

但是当我编译代码时,它不断崩溃,并且错误出现在 addlast 函数中。但我找不到我错在哪里。谁能告诉我 addlast 函数哪里出错了?

最佳答案

您的 makenode 函数有缺陷,它不会初始化结构中的所有元素。

您的 addlast 也有缺陷,因为当您添加第一个节点时,*ptrNULL 并且您正在取消引用temp->next 中的这个 NULL 指针,指向 undefined behavior .

关于c - 将节点插入到 LinkedList 中的最后一个位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28086637/

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