C 创建列表
函数读取包含正整数的输入文件,每行一个数字,并创建包含这些数字的列表,每个单元格一个-输入文件中的1表示列表结束。通过这种方式,您可以在同一输入文件中指定多个列表。假设输入文件称为“输入”。对函数的每次调用都会读取输入文件中的数字,直到达到-1,然后将这些数字放入列表,并返回指向此列表标题的指针。因此,如果输入文件包含 1 5 4 -1 4 8 6 -1 -1 7 8 然后,第一次调用函数将返回指向列表1->5->4->null的指针,第二次调用函数将返回指向列表4->8->6->null的指针。 第三次调用将返回null,第四次调用将返回7->8->null。我想实现这一点,到目前为止,我能够从文本文件中读取文件。现在,我希望对于每个-1遇到的fin文件,它都应该取-1之前的数字,并创建一个列表C 创建列表,c,linked-list,C,Linked List,函数读取包含正整数的输入文件,每行一个数字,并创建包含这些数字的列表,每个单元格一个-输入文件中的1表示列表结束。通过这种方式,您可以在同一输入文件中指定多个列表。假设输入文件称为“输入”。对函数的每次调用都会读取输入文件中的数字,直到达到-1,然后将这些数字放入列表,并返回指向此列表标题的指针。因此,如果输入文件包含 1 5 4 -1 4 8 6 -1 -1 7 8 然后,第一次调用函数将返回指向列表1->5->4->null的指针,第二次调用函数将返回指向列表4->8->6->null的指针
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct list {
char *string;
struct list *next;
};
typedef struct list LIST;
int main() {
FILE *fp;
char line[128];
LIST *current, *head;
head = current = NULL;
fp = fopen("test.txt", "r");
while (fgets(line, sizeof(line), fp)) {
LIST *node = (struct list * )malloc(sizeof(LIST));
node->string = _strdup(line);// strdup(line);//note : strdup is not standard function
node->next = NULL;
if (head == NULL) {
current = head = node;
}
else {
current = current->next = node;
}
}
fclose(fp);
//test print
for (current = head; current; current = current->next) {
printf("%s", current->string);
}
//need free for each node
return 0;
}
像这样:
#include <stdio.h>
#include <stdlib.h>
struct list {
int v;
struct list *next;
};
typedef struct list LIST;
LIST *makeListFromFile(FILE *fp){
int v;
LIST *current, *head = NULL;
while(fscanf(fp, "%d", &v) == 1 && v != -1){
LIST *node = malloc(sizeof(LIST));
node->v = v;
node->next = NULL;
if (head == NULL)
current = head = node;
else
current = current->next = node;
}
return head;
}
int main(void) {
FILE *fp = fopen("test.txt", "r");
while(!feof(fp)){
LIST *list = makeListFromFile(fp);
while(list){
LIST *temp = list->next;
printf("%d ", list->v);
free(list);
list = temp;
}
puts("NULL");
}
fclose(fp);
return 0;
}
我没有看到任何问题。这里的某个地方有一个问题?每个列表是否都存储到列表的列表中?不,它应该只打印列表,在这种情况下,正如您从示例输入中看到的,它应该创建4个列表,如示例中所述。我不熟悉使用c以及使用StackOverflow,如果在理解问题/格式时存在一些误解,请添加评论/建议,我将在否决表决前进行必要的更改。