/**********************************************
*file name: DoubleList.c
*function:设计双向链表
*author:[email protected]
*date:2024/4/23
*note:None
*CopyRight (c) 2023-2024 邮箱 All Right Reseverd
***********************************************/
//指的是单向链表中的结点有效数据类型,用户可以根据需要进行修改
typedef int DataType_t;
//构造链表的节点,节点链表中所有的数据类型都一样
typedef struct LinkedList
{
DataType_t data; //节点的数据域
struct DoubleLinkedList * next;
struct DoubleLinkedList * prev;
}DoubleLList_t;
//创建1个空的双链表
//创建一个空双向链表,头链表里应该有一个头节点,对链表进行初始化
DoubleLList_t * LList_Create(void)
{
//1.创建1个头节点并为头节点申请内存
DoubleLList_t * Head= (DoubleLList_t *)calloc(1,sizeof(DoubleLList_t));
if(NULL == Head)
{
perror("calloc memory for Head is failed");
exit(-1);
}
//2.对头节点进行初始化,头节点是不存储有效内容!!!
Head->next = NULL;
//3.把头节点的地址返回即可
return Head;
}
//创建双向链表的新结点,
DoubleLList_t *DoubleLList_Newnode(DataType_t data)
{
//1.创建1个新的结点并对新结点申请内存
DoubleLList_t * New = (DoubleLList_t *)calloc(1,sizeof(DoubleLList_t));
if(NULL == New)
{
perror("calloc memory for NewNode is failed!");
return NULL;
}
//2.对新节点的数据域和指针域进行初始化
New->data = data;
New->next = NULL;
New->prev = NULL;
return New;
}
//插入新结点
//1判断链表是否为空
if(Head->next == NULL)
Head->next = New;
//头插法
DoubleLList_t * DoubleLList_HeadInsert(DoubleLList_t *Head)
{
New->next= Head->next;
Head->next->prev = New;
Head->next = New;
return New;
}
//尾插
bool DoubleLList_LastInsert(DoubleLList_t *Head)
{//遍历
DoubleLList_t *Phead = Head
while(Phead->next)
{
Phead = Phead->next;
}
Phead->next = New;
New->prev = Phead;
printf("nenode Insert success!");
return true;
}
//指定位置插入
DoubleLList_LastInsert(DoubleLList_t *Head,DataType_t destval,DataType_t data )
{
//判断是否为空
if(Head->next == NULL)
Head->next = New;
//非空
DoubleLList_t *Phead = Head;
while(Phead->next)
{
Phead = Phead->next;
if(Phead->data == destval)
{
break;
}
}
New->next = Phead->next;
Phead->next->prve = New;
New->prev = Phead->next;
Phead->next =New;
printf("newnode Insert success!");
return true;
}
//双向链表的删除
bool DoubleLList_LastInsert(DoubleLList_t *Head)
{
//头删
//1先判断是否为空链表
if(Head->next == NULL)
printf("当前链表为空");
return false;
//2非空则进行链接
Head->next = Head->next->next;
Head->next->prve = NULL;
Head->next->next = NULL;
free(Head->next)
}
//尾删
bool DoubleLList_LastInsert(DoubleLList_t *Head)
{
DoubleLList_t *Phead = Head;
//1判断是否为空
if(Head->next == NULL)
Head->next = New;
//2遍历链表找到链表的尾节点
while(Phead->next)
{
Phead = Phead->next;
if(Phead->next == Head->next)
{
break;
}
}
//3 将尾结点的直接前驱指向NULL
Phead->prve = NULL;
//4 将尾结点的直接后继指向NULL
Phead->next->prve = NULL;
free(Phead);
}
//指定位置删结点
bool DoubleLList_LastInsert(DoubleLList_t *Head,DataType_t destval,DataType_t data)
{
//1先判断是否为空链表
if(Head->next == NULL)
printf("当前链表为空");
return false;
//1 遍历链表,找到待删除结点
while(Phead->next)
{
Phead = Phead->next;
if(Phead->data == destval)
{
break;
}
}
Phead->prve->next = Phead->next;
Phead->next->prve = Phead->prve;
free(Phead);
return true;
}