正如问题所指定的,我想将文本文件转换为链接列表。当我从数组中读取字符串元素时,它工作正常,但从文件中执行相同操作时会产生更新头的问题。以下是我尝试过的...
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
//creating structure
typedef struct node {
char *word;
struct node *next;
}node;
//function for creating a node
node *createnode(char *wrd){
node *temp1;
temp1 = (node*)malloc(sizeof(node));
temp1->word = wrd;
temp1->next = NULL;
return temp1;
}
//function for creating and adding new node to linked list
node *creat(node *head, char *wrd){
node *temp, *p;
temp = createnode(wrd);
if(head == NULL){
head = temp;
}else{
p = head;
while(p->next != NULL){
p = p->next;
}
p->next = temp;
printf("p->word from creat method: %s ADDR: %p HEAD: %s \n", p->word,
p->next,head->word);
}
return head;
}
//traverse the list and display each node
node *show(node *head){
node *p;
p=head;
while(p != NULL){
printf("from show method: %s", p->word);
p = p->next;
printf("\n");
}
printf("\n");
}
int main()
{
node *head = NULL;
/* Character array to read the content of file */
char sWord[20];
/* Pointer to the file */
FILE *fp;
/* Opening a file in r mode*/
fp= fopen ("hw10data.txt", "r");
while( fscanf(fp, "%s", sWord) != EOF )
{
head = creat(head, sWord); //create list
}
fclose(fp);
show(head);
return 0;
}
我不知道为什么每次插入时磁头都会更新。任何帮助将不胜感激。
最佳答案
改变的不是列表的头部;而是列表的头部。只是将值读入本地数组 sWord
,然后将其传递给 creat
和 createnode
函数。其中,您只是分配了一个指针,但没有复制sWord
的内容;因此,所有节点内容将指向相同的内存地址,即sWord
;当您读入新值时,所有节点内容都将指向该新值。所以看起来好像“头”已经变了。实际上所有节点都会显示相同的内容...
要解决这个问题,请在 createnode
中编写以下内容:
// temp1->word = wrd;
temp1->word = strdup(wrd);
或者,如果 strdup
不可用:
temp1->word = malloc(strlen(wrd)+1);
strcpy(temp1->word,wrd);
关于c - 将文本文件转换为 C 中的单链表时,每次插入都会更新 head,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49870800/