/********************************************************************************************************
*
* file name: Zqh_链表.c
* author : [email protected]
* date : 2024/05/05
* function : 链表的增删改查
* note : 模板
*
* Copyright (c) 2023-2025 [email protected] All right Reserved
* ******************************************************************************************************/
//指的是双向链表中的结点有效数据类型,用户可以根据需要进行修改
typedef int DataType_t;
//构造双向链表的结点,链表中所有结点的数据类型应该是相同的
typedef struct DoubleLinkedList
{
DataType_t data; //结点的数据域
struct DoubleLinkedList *prev; //直接前驱的指针域
struct DoubleLinkedList *next; //直接后继的指针域
}DoubleLList_t;
//创建一个空双向链表,空链表应该有一个头结点,对链表进行初始化
DoubleLList_t * DoubleLList_Create(void)
{
//1.创建一个头结点并对头结点申请内存
DoubleLList_t *Head = (DoubleLList_t *)calloc(1,sizeof(DoubleLList_t));
if (NULL == Head)
{
perror("Calloc memory for Head is Failed");
exit(-1);
}
//2.对头结点进行初始化,头结点是不存储数据域,指针域指向NULL
Head->prev = NULL;
Head->next = NULL;
//3.把头结点的地址返回即可
return Head;
}
//创建新的结点,并对新结点进行初始化(数据域 + 指针域)
DoubleLList_t * DoubleLList_NewNode(DataType_t data)
{
//1.创建一个新结点并对新结点申请内存
DoubleLList_t *New = (DoubleLList_t *)calloc(1,sizeof(DoubleLList_t));
if (NULL == New)
{
perror("Calloc memory for NewNode is Failed");
return NULL;
}
//2.对新结点的数据域和指针域(2个)进行初始化
New->data = data;
New->prev = NULL;
New->next = NULL;
return New;
}
//头插
bool DoubleLList_HeadInsert(DoubleLList_t*Head, DataType_t data)
{
//创建一个变量来保存头结点
DoubleLList_t* Phead = Head->next;
//1.创建新的结点,并对新结点进行初始化
DoubleLList_t* New = DoubleLList_NewNode(data);
if (NULL == New){
printf("can not insert new node\n");
return false;
}
//2.判断链表是否为空,如果为空,则直接插入即可
if (NULL == Head->next){
New->next = Head->next; //将首结点的地址给新结点的next指针
Head->next->prev= New;
Head->next = New;
return false;
}
New->next = Phead;
Phead->prev=New;
Head->next = New;
return false;
}
//删除目标结点
bool DoubleLList_DestInsert(DoubleLList_t*Head,DataType_t dest,DataType_t data)
{
DoubleLList_t* Phead = Head->next;
if (NULL == Head->next){
printf("双向链表为空,无法删除");
return false;
}
//循环查找需要删除的目标
while(Phead->data != dest){
if (NULL == Phead->next){
printf("只有一个首结点\n");
free(Phead);
return true;
}
Phead = Phead->next;
}
Phead->next->prev = Phead->prev;
Phead->prev->next = Phead->next;
Phead->prev = NULL;
Phead->next = NULL;
free(Phead);
return true;
}
int main(int argc, char const *argv[])
{
return 0;
}
标签:结点,Head,实现,DoubleLList,next,链表,Phead,双向,New
From: https://www.cnblogs.com/kencszqh/p/18176116