处理链表数组 [英] dealing with array of linked list

查看:18
本文介绍了处理链表数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的方法:

一个固定长度的数组(比如 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
",temp->data);
            temp = temp->next;
        }
    }
}

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

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,,??

更新::

在我编辑代码后(谢谢你),我认为是打印功能的问题,有什么想法吗?

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));

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

but the scope of q is limited to addNode(). You should have declared addNode() as

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

并相应地调整您的代码:

and adjust your code accordingly:

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

等等...

这篇关于处理链表数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆