我在使用这段代码时遇到了一些麻烦。当我在添加到列表后尝试打印列表时,它只打印最后一个元素。
* list,* temp和* new_node在本地声明。
if(list == NULL && new_node != NULL){
fprintf(fp1, "\r\nNew node1: %s %s %d %ld %d", new_node->op, new_node->name, new_node->tag, new_node->msgsize, new_node->weight);
list = (struct vertex*)malloc(sizeof(struct vertex));
list->name = new_node->name;
list->next = NULL;
list_of_vertices[rank] = list;
printf("changin list head\n");
//temp = list->next;
}
else{
if(new_node != NULL){
temp = list;
while(temp){
temp = temp->next;
}
temp = (struct vertex*)malloc(sizeof(struct vertex));
temp->name = new_node->name;
temp->next = NULL;
fprintf(fp1, "\r\nNew node: %s %s %d %ld %d", temp->op, temp->name, temp->tag, temp->msgsize, temp->weight);
}
}
编辑:以下代码也不起作用。它每次都会更改list的值,但我只进入if条件设置一次列表。
while(!feof(fp)){
fgets(read_line, 100, fp);
/*new node created by tokenizing string */
if(list == NULL && new_node != NULL){
fprintf(fp1, "\r\nNew node1: %s %s %d %ld %d", new_node->op, new_node->name, new_node->tag, new_node->msgsize, new_node->weight);
list = (struct vertex*)malloc(sizeof(struct vertex));
list->name = new_node->name;
list->next = NULL;
printf("list head\n %s", list->op); //prints only once when first line from file read
}
if(list != NULL)
printf("list head changed\n %s", list->name); // prints the name from the current read line.
}
答案 0 :(得分:1)
更改
while(temp){
temp = temp->next;
}
temp = (struct vertex*)malloc(sizeof(struct vertex));
到
while(temp->next){
temp = temp->next;
}
temp->next = (struct vertex*)malloc(sizeof(struct vertex));
temp = temp->next;
答案 1 :(得分:0)
修正了问题。我没有复制字符串值,而是使用指针(即a = b而不是strcpy(a,b),其中a和b是char数组)