C语言实现动态链表

【自学纪录】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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值