带头节点的双向循环链表part1(李慧芹视频案例)

视频链接https://www.bilibili.com/video/BV18p4y167Md?p=87&vd_source=a65c3b45fdf7ce45d3ec6422024bc43c

1、创建链表和删除链表函数

main.c文件

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "llist.h"

#define NAMESIZE 32

/* 声明普通节点下面挂的数据结构 */
typedef struct llist_score_s
{
	int  stuID;
	char name[NAMESIZE];
	int  math;
}LLIST_SCORE_S;

int main()
{
	/* 声明双向链表 */
	LLIST_HEAD_S* llist = NULL;

	/* 创建带头结点双向链表llist */
	llist = llist_create(sizeof(LLIST_SCORE_S));

	/* 删除链表 */
	llist_destroy(llist);

	return 0;
}

llist.c文件

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "llist.h"

/* 定义创建链表的函数 */
LLIST_HEAD_S* llist_create(int initsize)
{
	LLIST_HEAD_S* llist = NULL;

	llist = (LLIST_HEAD_S*)malloc(sizeof(*llist));
	if (NULL == llist)
		return NULL;

	llist->size = initsize;
	llist->head.data = NULL;
	llist->head.prev = &llist->head;
	llist->head.next = &llist->head;

	return llist;
}

/* 定义删除链表的函数 */
void llist_destroy(LLIST_HEAD_S* llist)
{
	LLIST_NODE_S* curnode;
	LLIST_NODE_S* next = NULL;

	for (curnode = llist->head.next; curnode != &llist->head; curnode = next)
	{
		next = curnode->next;
		free(curnode->data);
		free(curnode);
	}
	free(llist);
}

llist.h文件

#ifndef LLIST_H_
#define LLIST_H_

#define NAMESIZE  32

/* 定义普通节点的类型 */
typedef struct llist_node_s
{
	void* data;
	struct llist_node_s* prev;
	struct llist_node_s* next;
}LLIST_NODE_S;

/* 定义头节点的类型 */
typedef struct llist_head_s
{
	int size;
	LLIST_NODE_S head;
}LLIST_HEAD_S;

/* 声明创建链表的函数,本质是创建头节点*/
LLIST_HEAD_S* llist_create(int initsize);

/* 声明删除链表的函数*/
void llist_destroy(LLIST_HEAD_S * llist);

#endif
posted @ 2022-09-25 20:46  轩邈、  阅读(27)  评论(0编辑  收藏  举报