这个内存的的控制难道头了,哪位路过指点指点
#include <stdio.h>#include <stdlib.h>
typedef struct node
{
int item;
struct node* next;
} NODE;
NODE *insert(NODE *head, int num);
NODE *search(NODE *head, int num);
void destroy(NODE *head);
int main()
{
NODE *head = NULL, *p;
int num;
while(scanf("%d", &num)!=EOF) {
head = insert(head, num);
}
for(p=head;p!=NULL;p=p->next) {
printf("%d ", p->item);
}
printf("\n");
int count=0;
for(p=head;p!=NULL;p=p->next) {
if((p=search(p, 100))!=NULL) count++;
else break;
}
printf("num of 100 is %d.\n", count);
destroy(head);
}
NODE *insert(NODE *head, int num)
{
NODE *p = malloc(sizeof(NODE));
if(p == NULL) {printf("error!\n");exit(1);}
p->item = num;
p->next = head;
return p;
}
NODE *search(NODE *head, int num)
{
NODE *p;
for(p=head;p!=NULL;p=p->next) {
if(p->item == num) break;
}
return p;
}
void destroy(NODE *head)
{
NODE *p,*q;
for(p=head;p!=NULL;p=q) {
q=p->next;
free(p);
}
}
在这个程序中作进一步改进
要求实现函数delete从链表中摘除用search找到的节点,最后调用free释放它的存储空间