处理链表数组

Ram*_*rar 7 c arrays linked-list

我的方法:

每个元素的固定长度(假设为20)数组是指向链表的第一个节点的指针.所以我有20个不同的链表.

这是结构:

struct node{
       char data[16];
       struct node *next;
};
Run Code Online (Sandbox Code Playgroud)

我对该数组的声明

struct node *nodesArr[20];
Run Code Online (Sandbox Code Playgroud)

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

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")
Run Code Online (Sandbox Code Playgroud)

addNode函数:

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; 
}
Run Code Online (Sandbox Code Playgroud)

并从链表列表中打印数据,我这样做:

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在编译器没有错误,程序运行,我将数据传递给它,当我打电话打印它不打印任何东西,??

更新::

在我编辑代码(thx for you)之后,我认为打印功能中的问题,任何想法?

thk*_*ala 5

问题在于addNode().当列表为空时,您执行以下操作:

q = malloc(sizeof(struct node));
Run Code Online (Sandbox Code Playgroud)

但范围q仅限于addNode().你应该声明addNode()

void addNode(struct node **q, char *d)
Run Code Online (Sandbox Code Playgroud)

并相应地调整您的代码:

*q = malloc(sizeof(struct node));
Run Code Online (Sandbox Code Playgroud)

等等...