69,371
社区成员
发帖
与我相关
我的任务
分享
#define __WIN
//VS中的内存检测
#ifdef __WIN
#define _CRTDBG_MAP_ALLOC
#include<stdlib.h>
#include<crtdbg.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
#define __DEBUG__
typedef void* (*list_func)(void* x);
typedef enum _node_type
{
INT,
STRING,
DOUBLE
} node_type;
typedef struct _node node;
struct _node
{
node *next;
void *v;
size_t len;
node_type t;
};
//创建节点
node *creat_node(size_t n,node_type t)
{
node *tmp;
tmp = (node*)malloc(sizeof(node));
tmp->next = NULL;
tmp->len = n;
tmp->v = malloc(tmp->len);
tmp->t = t;
memset(tmp->v,0,tmp->len);
return tmp;
}
//添加节点
node *list_add(node *parent,void* v,node_type t)
{
node *tmp;
node *cur;
unsigned char len = 0;
//通过节点类型,判断大小
switch(t)
{
case STRING:
len = strlen((char*)v) + 1;
break;
case INT:
len = sizeof(int);
break;
case DOUBLE:
len = sizeof(double);
break;
}
//创建节点,给出所占内存大小
tmp = creat_node(len,t);
//tmp->v = v;
//这里不能用memset函数,它是按字节对指针进行改变的,只会复制过去第一个字节,该选用memcpy
// memset(tmp->v,v,sizeof(v));
memcpy(tmp->v,v,len);
if(parent != NULL)
{
cur = parent;
while(cur->next != NULL) cur = cur->next;
cur->next = tmp;
}
return tmp;
}
node *list_remove(node *parent,int v)
{
return 0;
}
void output(node *n)
{
switch(n->t)
{
case INT:
printf("%d\r\n",*(int*)(n->v));
break;
case STRING:
printf("%s\r\n",(char*)n->v);
break;
case DOUBLE:
printf("%.2f\r\n",*(double*)n->v);
break;
}
}
//按照书上写的,将链表中的字符转换为大写
void set_member_to_upper(node *n)
{
int i;
char *p;
if(n->t == STRING)
{
p = (char*)n->v;
for(i = 0; p[i] != '\0'; p[i] = toupper(p[i]), i++);
}
}
//销毁链表
node *list_destroy(node *parent)
{
node *tmp = NULL;
node *cur = parent;
#ifdef __DEBUG__
puts("kill");
#endif
while(cur != NULL)
{
tmp = cur->next;
#ifdef __DEBUG__
//puts("kill one");
//printf("%s\r\n",(char*)cur->v);
//output(cur);
#endif
free(cur->v);
free(cur);
cur = tmp;
}
return 0;
}
//遍历链表中的数据项
int list_foreach(node *parent,list_func lf)
{
node *cur;
for(cur = parent; cur != NULL; lf(cur),cur = cur->next);
return 0;
}
int main()
{
int n = 50;
double x;
char *pstr = (char*)malloc(10);
node *list = list_add(NULL,strdup("a"),STRING);
list_add(list,strdup("abcdef"),STRING);
list_add(list,strdup("aadsfdfg"),STRING);
/*list_add(list,&n,INT);
n = 60;
list_add(list,&n,INT);
n = 70;
list_add(list,&n,INT);
n = 500;
list_add(list,&n,INT);
x = 9.00009;
list_add(list,&x,DOUBLE);*/
//for(i = 1; i < 5;list_add(list,i * 2),i++);
// list_foreach(list,output);
//list_foreach(list,set_member_to_upper);
//list_foreach(list,output);
free(pstr);
list_destroy(list);
system("pause");
_CrtDumpMemoryLeaks();
return 0;
}