花了半个小时写了一个“教学版”的链表,所谓教学版就是说该代码比较简陋,只是为了说明一些链表的性质,不具有实用价值。
以下代码未经调试以及单元测试系统测试,如运行错误,纯属正常。
头文件:
#ifndef _LINKLIST_H_
#define _LINKLIST_H_
typedef void* LIST;
typedef void* DATA;
typedef unsigned int uint;
typedef void (*fnCallback)(DATA data);
LIST create();
bool append(LIST list, DATA data);
uint length(LIST list);
DATA del(LIST list, uint index);
DATA modify(LIST list, uint index, DATA data);
DATA get(LIST list, uint index);
void release(LIST list, fnCallback func);
#endif
源文件:
#include "malloc.h"
#include "LinkList.h"
typedef struct linkNode
{
void * data;
linkNode *pNext;
}linkNode;
#define NULL 0
LIST create()
{
linkNode *node = (linkNode*)malloc(sizeof(linkNode));
node->data = NULL;
node->pNext = NULL;
return (LIST)node;
}
uint length(LIST list)
{
uint len = 0;
linkNode *node = NULL;
for(node=(linkNode*)list; node->pNext; len++, node=node->pNext);
return len;
}
bool append(LIST list, DATA data)
{
linkNode *node = NULL;
for(node = (linkNode*)list; node->pNext; node = node->pNext);
node->data = data;
node->pNext = NULL;
return true;
}
DATA del(LIST list, uint index)
{
linkNode *node = NULL;
linkNode *temp = NULL;
void * data = NULL;
if(index >= length(list))
return false;
for(node = (linkNode*)list ; index--; node = node->pNext);
temp = node->pNext;
data = temp->data;
node->pNext = temp->pNext;
free(temp);
return data;
}
DATA modify(LIST list, uint index, DATA data)
{
linkNode *node = NULL;
void *temp = NULL;
if(index >= length(list))
return false;
for(node = (linkNode*)list ; index--; node = node->pNext);
temp = node->pNext->data;
node->pNext->data = data;
return temp;
}
DATA get(LIST list, uint index)
{
return del(list, index);
}
void release(LIST list, fnCallback func)
{
linkNode *node = NULL;
linkNode *temp = NULL;
void * data = NULL;
for(node=(linkNode*)list; node; )
{
temp = node->pNext;
node = temp->pNext;
func(temp->data);
free(temp);
}
free(list);
}