【自学纪录】C语言实现动态链表,也是最简单的动态链表实现方法
#include "linklist.h"
struct linkNode
{
struct link* next;
};
struct linkList
{
struct linkNode header;
int size;
};
//初始化链表
void* initLinkList()
{
struct linkList* list = malloc(sizeof(struct linkList));
list->size = 0;
list->header.next = NULL;
return list;
}
//插入节点
void insert(void* list, int pos, void* data)
{
if (list==NULL)
{
return;
}
if (NULL==data)
{
return;
}
struct linkList* mylist = (struct linkList *)list;
if (pos<0 || pos>mylist->size)
{
pos = mylist->size;
}
struct linkNode* newnode = (struct linkNode*)data;
struct linkNode* pCurrent = &(mylist->header);
for (int i = 0; i < pos; i++)
{
printf("ddddddddddddd\n");
pCurrent = pCurrent->next;
}
newnode->next = pCurrent->next;
pCurrent->next = newnode;
mylist->size++;
}
//遍历链表
void foreach(void* list, void(*myforeach)(void*))
{
if (NULL==list)
{
return;
}
if (myforeach==NULL)
{
return;
}
struct linkList* mylist = list;
struct linkNode* pCurrent = mylist->header.next;
while (pCurrent!=NULL)
{
myforeach(pCurrent);
pCurrent = pCurrent->next;
}
}
//按位置删除
void removeByPos(void* list, int pos)
{
if (NULL==list)
{
return;
}
struct linkList* mylist = list;
if (pos<0 || pos>=mylist->size-1)
{
return;
}
struct linkNode* pCurrent = &(mylist->header);
struct linkNode* pDel = NULL;
for (int i = 0; i <pos; i++)
{
pCurrent = pCurrent->next;
}
pDel = pCurrent->next;
pCurrent->next = pDel->next;
mylist->size--;
}
//大小
int size(void* list)
{
if (NULL==list)
{
return;
}
struct linkList* mylist = list;
return mylist->size;
}
//销毁链表
void destroy(void* list)
{
if (NULL==list)
{
return;
}
struct linkList* mylist = list;
free(mylist);
mylist = NULL;
}
struct Person
{
struct linkNode node;
char name[128];
int age;
};
void myforeach(void* data)
{
struct Person* mydata = data;
printf("%s %d\n",mydata->name,mydata->age);
}
test()
{
//初始化链表
void* list = initLinkList();
//创建数据
struct Person p1 = { NULL,"aaa",10 };
struct Person p2 = { NULL,"bbb",20 };
struct Person p3 = { NULL,"ccc",30 };
struct Person p4 = { NULL,"ddd",40 };
struct Person p5 = { NULL,"eee",50 };
//插入链表
insert(list,0,&p1);
insert(list,0,&p2);
insert(list,0,&p3);
insert(list,0,&p4);
insert(list,0,&p5);
//遍历链表
foreach(list,myforeach);
removeByPos(list,2);
printf("-----------------\n");
foreach(list,myforeach);
}
int main(void)
{
test();
system("pause");
return EXIT_SUCCESS;
}