/*--------------------------------list.h--------------------------------*/

/*
Remember:
If you want to delete a node or a list,
you should delete things that in this node or in this list at first.
You don't need to use function list_add.
Use typedef when you have a complex type!
*/

#ifndef	_LIST_H
#define	_LIST_H

#define	LIST_LAST	-1

struct NODE {
	void *value;
	struct NODE *next;
};

#ifdef	__cplusplus
extern "C"{
#endif

void **node_look(struct NODE *root,int number);
int node_add(struct NODE **root,int number,void *value);
int node_delete(struct NODE **root,int number);
struct NODE *list_add(void);
void list_delete(struct NODE *root);

#ifdef	__cplusplus
}
#endif

#define	TYPELIST(name,type)	\
	type **name##$node_look(struct NODE *root,int number)	\
		{return (type **)node_look(root,number);}	\
	int name##$node_add(struct NODE ** root,int number,type *value)	\
		{return node_add(root,number,value);}

#endif	//!defined(_LIST_H)

/*--------------------------------list.c--------------------------------*/

#include	"list.h"
#include	<stdlib.h>
#include	<assert.h>

struct PNODES {
	struct NODE *pthis;
	struct NODE *plast; 
};
typedef enum {
	LE_SUCCESS,
//	LE_FAILURE,
	LE_NOT_FOUND,
	LE_EMPTY
}list_exits;

//查找节点的指针 
static list_exits node_find(struct NODE *root,
	int number,struct PNODES *pnode)
{
	assert(pnode!=NULL);//help debug
	pnode->pthis=root;//初始化 
	pnode->plast=NULL;
	int n;
	
	if(pnode->pthis==NULL)return LE_EMPTY;//处理空链表 
	for(n=0;n!=number;n++)//检索(从0开始) 
	{
		if(pnode->pthis->next==NULL)//到达列表末尾 
			if(number<0)return LE_SUCCESS;//返回最后一项 
			else return LE_NOT_FOUND;
		pnode->plast=pnode->pthis;//指针调整 
		pnode->pthis=pnode->pthis->next;
	}
	return LE_SUCCESS;
}

//查找节点 
void **node_look(struct NODE *root,int number)
{
	struct PNODES p;
	list_exits f;
	f=node_find(root,number,&p);
	if(f==LE_SUCCESS)return &p.pthis->value;
	return NULL;
}

//添加节点 
int node_add(struct NODE **root,int number,void *value)
{
	struct PNODES p;
	list_exits f;
	f=node_find(*root,number,&p);
	if(f==LE_NOT_FOUND||number<0)//超出范围就追加 
	{
		p.plast=p.pthis;
		p.pthis=NULL;
	}
	struct NODE *n=(struct NODE *)malloc(sizeof(struct NODE));
	if(n==NULL)return 0;//报错 
	if(f==LE_EMPTY||number==0)*root=n;//处理前一个节点 
	else p.plast->next=n;
	n->next=p.pthis;//处理后一个节点 
	n->value=value;//处理内容 
	return 1;
}

//删除节点 
int node_delete(struct NODE **root,int number)
{
	struct PNODES p;
	list_exits f;
	f=node_find(*root,number,&p);
	if(f!=LE_SUCCESS)return 0;
	if(number==0)*root=p.pthis->next;//处理前一个节点 
	else p.plast->next=p.pthis->next;
	free(p.pthis);
	return 1;
}

//新建列表 
struct NODE *list_add(void)
{
	return NULL;
}

//删除列表 
void list_delete(struct NODE *root)
{
	struct PNODES p;
	p.pthis=root;//初始化 
	p.plast=NULL;
	
	if(root==NULL)return;//空列表 
	do
	{
		p.plast=p.pthis;//推进 
		p.pthis=p.pthis->next;
		free(p.plast);//删除节点 
	}while(p.pthis!=NULL);
}