处理链表数组
我的方法:
每个元素的固定长度(假设为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")
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; }
并从链表列表中打印数据,我这样做:
void print(){ int i; struct node *temp; for(i=0 ; i data); temp = temp->next; } } }
现在编译器没有错误,程序运行,我将数据传递给它,当我打电话打印它不打印任何东西,??
更新::
在我编辑代码(thx for you)之后,我认为打印function中的问题,任何想法?
问题在于addNode()
。 当列表为空时,您执行以下操作:
q = malloc(sizeof(struct node));
但q
的范围仅限于addNode()
。 您应该将addNode()
声明为
void addNode(struct node **q, char *d)
并相应地调整您的代码:
*q = malloc(sizeof(struct node));
等等…
当您将struct node *q
传递给addNode
您将为其提供数组中元素的地址。 如果你在里面使用malloc
,那么你将覆盖这个变量q
,它是函数的本地变量,现在指向不同的变量,但你还没有改变原始数组。 尝试使用指向节点的指针( struct node **q
)。
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
新节点,则数组中的值将设置为指向新节点。
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]; } }