gpt4 book ai didi

c - 我的单链表代码有什么问题?

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

我正在用 C 编写单向链表。这是我到目前为止所写的内容。

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

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


struct Node* init()
{
struct Node* head=NULL;
head=malloc(sizeof(struct Node));
head->value=-1;
return head;

}



int length(struct Node* head)
{
struct Node* current=head;
int length=0;
while(current!=NULL)
{
length++;
current=current->next;

}
return length;

}


void print(struct Node* head)
{
int i=0;
int len=length(head);
for(i=0;i<len;i++)
{
printf("%d%d",i,head[i].value);
printf("\n");


}


}




struct Node* insert(int data,struct Node* head)
{
struct Node* current=NULL;
if(length(head) > 0)
{
int val=head->value;
if (val==-1)
{
head->value=data;
head->next=NULL;

}
else
{
current=malloc(sizeof(struct Node));
current->value=data;
current->next=head;
head=current;


}

}
else
{
printf("List is empty");

}

return head;


}

int main()
{

/* printf("Hello"); */
struct Node *head=init();

head=insert(20,head);
head=insert(30,head);
head=insert(40,head);

print(head);
printf("%d",length(head));

return 0;

我得到的输出值是:指标值0 401 02 0

长度为 3。我无法理解我在指针操作中做错了什么。

最佳答案

一个明显的问题是在初始化时没有在 NULL 旁边设置——在检查空列表的长度时会失败

但你真正的问题是打印功能

你不能使用:

head[i].value

该符号仅对数组有效,您需要使用 next 来查找每个成员

关于c - 我的单链表代码有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12550125/

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