2011-02-09 88 views
7

我的方法:处理链表的阵列

固定长度的数组(可以说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 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; 
     } 
    } 
} 

现在编译器会发出任何错误,程序运行和我的数据传递给它,当我打电话打印它不打印任何东西,, ??

更新::

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

+1

你试过踩着它通过一个调试器,或添加有用'printf'报表? –

+0

是啊我试过了,但我什么都没有 –

+1

你什么都没有?例如,你不能发现'nodesArr'的所有元素在什么时候变成了'NULL'? –

回答

5

问题出在addNode()。当列表为空你做:

q = malloc(sizeof(struct node)); 

q的范围仅限于addNode()。你刚才应该申报addNode()作为

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

,并相应地调整你的代码:

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

等等...

+0

这样q = q->下一个,应该是这样的,* q = * q-> next,或者(* q) - > next? –

+0

如果让它更容易,一旦分配完毕,您可以将指向地址分配给单个指针,并将代码的其余部分或多或少地保存为现在的样子。 'struct node * sp;'然后'sp = * q' –

+0

@Rami Jarrar:您必须使用'* q =(* q) - > next'。 C大师会[告诉你](http://www.difranco.net/cop2220/op-prec.htm)' - >'比取消引用操作符具有更高的优先级。我们其他人只是使用一对括号,不用再考虑它了。 – thkala

3

当你通过struct node *qaddNode你给它一个数组元素的地址。如果你在里面使用malloc,那么你将覆盖这个变量q,它是该函数的局部变量,现在指向不同的东西,但是你并没有改变你的原始数组。尝试使用指向节点的指针(struct node **q)。

2
void addNode(struct node *q, char *d){ 
    if(q == NULL) 
     q = malloc(sizeof(struct node)); 

这里的问题。

q的新值不会超出该函数,因此您的链接列表数组永远不会更新。

通常这里的解决方案是使用双指针:

void addNode(struct node **q, char *d){ 
    if(*q == NULL) 
     *q = malloc(sizeof(struct node)); 

,并调用它像这样:

addNode(&nodesArr[i],word); 

然后,如果你malloc一个新的节点,数组中的价值将被设置为指向新节点。

-2
struct node 
{ 

    int actual, estimated; 

    char c; 

    struct node *next; 

} *head[4], *var[4], *trav[4]; 


void 
insert_at_end (char c, int value, int value1) 
{ 

    struct node *temp; 

    temp = head[i]; 

    var[i] = (struct node *) malloc (sizeof (struct node)); 

    var[i]->actual = value; 

    //var1=(struct node *)malloc(sizeof(struct node)); 

    var[i]->estimated = value1; 

    var[i]->c = c; 

    //printf("%d",var->estimated); 

    if (head[i] == NULL) 

    { 

     head[i] = var[i]; 

     head[i]->next = NULL; 

    } 

    else 

    { 

     while (temp->next != NULL) 

    { 

     temp = temp->next; 

    } 

     var[i]->next = NULL; 

     temp->next = var[i]; 

    } 

}