链接列表存储从1到1000的素数
正如您将在以下程序的注释中看到的那样,我应该创建一个列表,存储从1到1000的所有素数并释放节点。
只有两个function是我的工作。 但是,我还没弄清楚为什么这个程序不能编译。 你们看到了这个错误吗? 这是一个已经交完的作业,所以这仅供我个人参考。
#include #include #include /* given data structure declaration */ struct record { int data; struct record * next; }; typedef struct record RecordType; /* DO NOT MODIFY */ /* print a list */ void print_list(RecordType * list) { RecordType * visitor = list; int count = 0; while (visitor != NULL) { printf("%d ", visitor->data); visitor = visitor->next; count++; } printf("\n"); printf("There are %d items in the list.\n", count); } /* MY WORK HERE */ /* free every node in the list */ void free_list(RecordType * list) { while (list->data != 2){ free(list->next); list->next = list; } } /* MY WORK HERE */ /* this function may call other functions created by students */ /* create a list storing all prime numbers in [1, 1000] in ascending order */ /* return a pointer to the starting point of the list */ RecordType * create_list_prime_in_1_to_1000() { RecordType * begin, *tail, *temp; int i = 0; begin = malloc(sizeof(RecordType)); begin->data = 0; begin->next = NULL; tail = begin; while(i data = ++i; tail -> next = temp; tail -> temp; tail -> next = NULL; } } int isPrime(int n){ int d; for (d = 2; d data = 2; start->next = malloc(sizeof(RecordType)); start->next->data = 3; start->next->next = malloc(sizeof(RecordType)); start->next->next->data = 5; start->next->next->next = malloc(sizeof(RecordType)); start->next->next->next->data = 7; start->next->next->next->next = NULL; print_list(start); free_list(start); /* i am expected to expected to build a list iteratively rather than hard-code */ start = create_list_prime_in_1_to_1000(); print_list(start); free_list(start); return 0; }
您将tail
声明为:
RecordType * begin, *tail, *temp;
和RecordType
为:
struct record { int data; struct record * next; }; typedef struct record RecordType;
接下来你有:
tail -> temp;
这不起作用,因为RecordType
没有名为temp的成员。
我认为它应该是:
tail = temp;
运行时错误的原因似乎是因为:
void free_list(RecordType * list) { while (list->data != 2){ free(list->next); list->next = list; } }
哪个不对。 你需要这样的东西:
void free_list(RecordType * list) { // keep going till there are nodes. while (list){ // save the link to the rest of the nodes. RecordType *temp = list->next; // free the current node. free(list); // repeat the process starting at the next node. list = temp; } }