处理链表阵列 [英] dealing with array of linked list
问题描述
我的方法:
固定长度的数组(可以说20)的每个元素是指向一个链表的第一个节点。
所以我有20个不同的链接列表。
An array of fixed-length (lets say 20) each element is pointer to the first node of a linked list. so i have 20 different linked list.
这是结构:
struct node{
char data[16];
struct node *next;
};
我声明数组
struct node *nodesArr[20];
现在,一个新的节点添加到链表中的一个,我这样做:
now to add a new node to one of the linked list, i do this:
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")
该ADDNODE功能:
The addNode function:
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;
}
和从链表的阵列打印数据,我这样做:
and to print data from the array of linked list, i do this:
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;
}
}
}
现在的编译器没有给出错误,程序运行和我的数据传递给它,当我打电话打印不打印任何东西,, ??
now compiler gives no error, the program run and i pass the data to it, and when i call print it doesn't print any thing,,??
更新:
我编辑了code(感谢你),我觉得在打印功能的问题,,任何想法?
after I edited the code (thx for you), i think the problem in the print function,, any idea ?
推荐答案
问题就出在 ADDNODE()
。当列表为空你做的:
The problem lies in addNode()
. When the list is empty you do:
q = malloc(sizeof(struct node));
但①
的范围仅限于 ADDNODE()
。你刚才应该申报 ADDNODE()
为
but the scope of q
is limited to addNode()
. You should have declared addNode()
as
void addNode(struct node **q, char *d)
并相应地调整你的code:
and adjust your code accordingly:
*q = malloc(sizeof(struct node));
等等...
这篇关于处理链表阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!