解决释放问题
程序目的如图:程序代码如下:
程序代码:
#include <stdio.h> #include <stdlib.h> #define LEN sizeof(NodeList) struct NodeList { int number; NodeList *next; }; void OutputList(NodeList *); NodeList *CreateList(int a[], int ); NodeList *DeleteList(NodeList *); int main() { int array[100] ; int length = 0; NodeList *head; char ch; printf("Please input a number sequence:\n"); do { scanf("%d", &array[length++]); ch = getchar(); }while (ch != '\n'); head = CreateList(array, length); printf("The original list is:\n"); OutputList(head); printf("\n"); printf("The list after delete is:\n"); DeleteList(head); OutputList(head); printf("\n"); return 0; } NodeList *CreateList(int a[], int length) { NodeList *head, *p1, *p2; int i = 0; head = p1 = p2 = (NodeList *)malloc(LEN); do{ p2 -> number = a[i++]; p1 = (NodeList *)malloc(LEN); p2 -> next = p1; p2 = p1; }while (i < length); p2 -> next = NULL; return head; } void OutputList(NodeList *head) { NodeList *p; p = head; while (p -> next != NULL) { printf("%d ", p -> number); p = p -> next; } } NodeList *DeleteList(NodeList *head) { NodeList *p1, *p2, *p3; p3 = p2 = head; p1 = p3 -> next; while (p3 -> next != NULL) { while (p1 != NULL) { if (p1 -> number == p3 -> number) { p1 = p1 -> next; p2 -> next = p1; } else { p2 = p1; p1 = p1 -> next; } } p3 = p2 = p3 -> next; p1 = p3 -> next; } return head; }我现在的问题是,CreateList()函数使用malloc()申请了内存,为了不使内存泄露必须手动free();那么是在主函数中释放还是在子函数中释放?由于是一个链表,那么怎么释放每一个结点内存?我看到很多程序就直接写个
free(p)完事,这能达到目的吗?比如我上面的程序,怎么释放?