gpt4 book ai didi

c - 处理链表数组

转载 作者:太空狗 更新时间:2023-10-29 17:10:17 25 4
gpt4 key购买 nike

我的方法:

一个固定长度的数组(比方说 20 个),每个元素都是指向链表第一个节点的指针。所以我有 20 个不同的链表。

这是结构:

struct node{
char data[16];
struct node *next;
};

我对该数组的声明

struct node *nodesArr[20];

现在要将新节点添加到链表之一,我这样做:

struct node *temp;

temp = nodesArr[i]; // i is declared and its less than 20
addNode(temp,word); // word is declared (char *word) and has a value ("hello")

添加节点函数:

void addNode(struct node *q, char *d){
if(q == NULL)
q = malloc(sizeof(struct node));
else{
while(q->next != NULL)
q = q->next;

q->next = malloc(sizeof(struct node));
q = q->next;
}

q->data = d; // this must done using strncpy
q->next = NULL;
}

为了打印链表数组中的数据,我这样做了:

void print(){
int i;
struct node *temp;

for(i=0 ; i < 20; i++){
temp = nodesArr[i];
while(temp != NULL){
printf("%s\n",temp->data);
temp = temp->next;
}
}
}

现在编译器没有给出错误,程序运行并且我将数据传递给它,当我调用打印时它没有打印任何东西,,??

更新::

在我编辑了代码之后(谢谢你),我认为打印函数有问题,有什么想法吗?

最佳答案

问题出在addNode()。当列表为空时,您可以:

q = malloc(sizeof(struct node));

但是q的范围仅限于addNode()。您应该将 addNode() 声明为

void addNode(struct node **q, char *d)

并相应地调整您的代码:

*q = malloc(sizeof(struct node));

等等……

关于c - 处理链表数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4940043/

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