#include <stdio.h>
#include <stdlib.h>
#define LEN sizeof(struct LNode)
int num=20;
struct LNode
{
int num;
struct LNode* next;
};
struct LNode* talloc(void)
{
return (struct LNode*)malloc(LEN);
}
void dateget(struct LNode *_root)
{
_root->num = num++;
_root->next = NULL;
}
struct LNode *addroot(struct LNode *_root)
{
struct LNode *p = NULL, *p2 = NULL;
if(_root == NULL)
{
_root = talloc();
dateget(_root);
}
else
{
for(p=_root; p->next != NULL; p=p->next)
;
p2 = talloc();
dateget(p2);
p->next = p2;
}
return _root;
}
struct LNode *kill(struct LNode *_root, int num)
{
struct LNode *p=_root, *p2=NULL;
if(p->num == num)
{
_root = _root->next;
free(p);
}
else
{
for(;p->next->num != num && p->next != NULL; p=p->next)
;
if(p->next->num == num)
{
p2 = p->next;
p->next = p->next->next;
free(p2);
}
}
return _root;
}
main()
{
struct LNode *_root = NULL;
char i;
for(i=0; i < 10; i++)
{
_root = addroot(_root);
}
//for(i=20; i < 30; i++)
{
/*_root = */kill(_root,20); //我杀死头结点
}
for(; _root != NULL && _root->next != NULL ; _root=_root->next)
{
printf("_root=%x next=%x num=%d\n",_root, _root->next, _root->num);
}
printf("_root=%x next=%x num=%d\n",_root, _root->next, _root->num);
}
_root=273768 next=273788 num=0 //我让主函数_root仍然指向刚才释放的头结点
_root=273788 next=273798 num=21
_root=273798 next=2737a8 num=22
_root=2737a8 next=2737b8 num=23
_root=2737b8 next=2737c8 num=24
_root=2737c8 next=2737d8 num=25
_root=2737d8 next=2737e8 num=26
_root=2737e8 next=2737f8 num=27
_root=2737f8 next=273808 num=28
_root=273808 next=0 num=29
Press any key to continue...
刚回家,把这个链表kill函数写好了,我想问的是 free怎么释放结构体指针的
struct LNode
{
char* date;
int size;
int num;
struct LNode* next;
}*root; //结构体“指针变量”刚才没把这个指针打进去......
root = (struct LNode*)malloc(LEN);
root->date = (char *)malloc(20);
root->size = 100;
root->num=200;
free(root);
这样编译器给我释放的是怎么样的空间
[此贴子已经被作者于2006-5-16 17:34:32编辑过]