求个关于链表释放的问题 。
写了一个用链表输出1-N之间素数的程序 结果应该没错 但是在释放删除结点和遍历释放时出错了可是俺不知道怎么改 求大牛指教。
程序代码:
/* Print the prime numbers between 1-N */ #include <stdio.h> #include <stdlib.h> #include <math.h> #define N 1000 #define M (int)sqrt((double)N) typedef struct Node { int num; struct Node *next; }SNode, *LinkList; LinkList CreateList(LinkList head); void PrintPrime(LinkList head); LinkList GetPrimes(LinkList head); void FreeList(LinkList head); int main(void) { LinkList head = NULL; head = CreateList(head); GetPrimes(head); PrintPrime(head); //FreeList(head); 加这个会出错 return 0; } LinkList CreateList(LinkList head) { LinkList p, q; if (NULL == head) { head = (LinkList)malloc(sizeof(LinkList)); if (NULL == head) { printf("Memory allocation error!\n"); return NULL; } } head->next = NULL; p = (LinkList)malloc(sizeof(LinkList)); if (NULL == p) { printf("Memory allocation error!\n"); return NULL; } p->num = 2; head->next = p; p->next = NULL; int i; for (i = 3; i <= N; i += 2) { q = (LinkList)malloc(sizeof(LinkList)); if (NULL == q) { printf("Memory allocation error!\n"); return NULL; } q->num = i; q->next = p->next; p->next = q; p = p->next; } return head; } void PrintPrime(LinkList head) { LinkList p; int count = 0; if (NULL == head || NULL == head->next) { printf("This is an empty linklist!\n"); return; } p = head->next; while (NULL != p) { printf("%-6d", p->num); p = p->next; count++; if (0 == count % 10) printf("\n"); if (0 == count %200) getchar(); } printf("\nThere are %d prime nunbers.\n", count); } LinkList GetPrimes(LinkList head) { LinkList p, pre, div; div = head->next->next; while (div->num <= M) { pre = div; p = div->next; while (NULL != p) { if (0 == ((p->num) % (div->num))) { pre->next = p->next; //free(p); 加这个也会错 p = pre->next; } else { pre = pre->next; p = p->next; } } div = div->next; } return head; } ////// 难道我释放函数写错了 貌似没问题啊 void FreeList(LinkList head) { LinkList p; if (NULL == head) return; else { while (NULL != head) { p = head; head = head->next; free(p); } } }百分求解
[ 本帖最后由 有容就大 于 2012-11-26 23:19 编辑 ]