双向循环链表的实现

/********************************************************************************************************
*
*	file name:	Zqh_链表.c
* 	author	 :	keyword2024@163.com
* 	date	 :	2024/05/05
*	function :	链表的增删改查
*	note	 :	模板
*	
*  Copyright (c)  2023-2025   keyword2024@163.com    All right Reserved
* ******************************************************************************************************/



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

//指的是双向循环链表中的结点有效数据类型,用户可以根据需要进行修改
typedef int  DataType_t;

//构造双向循环链表的结点,链表中所有结点的数据类型应该是相同的
typedef struct DoubleLinkedList
{
	DataType_t  		     data; //结点的数据域
	struct DoubleLinkedList	*prev; //直接前驱的指针域
	struct DoubleLinkedList	*next; //直接后继的指针域

}DoubleLList_t;




//创建一个空双向循环链表,空链表应该有一个头结点,对链表进行初始化
DoubleLList_t * DoubleCirLList_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.对头结点进行初始化,头结点是不存储数据域,指针域指向自身即可,体现“循环”
	Head->prev = Head;
	Head->next = Head;

	//3.把头结点的地址返回即可
	return Head;
}



//创建新的结点,并对新结点进行初始化(数据域 + 指针域)
DoubleLList_t * DoubleCirLList_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 = New;
	New->next = New;

	return New;
}


//双向循环链表头插
bool  insertCirDoublyLinList(DoubleLList_t*Head, DoubleLList_t*New)
{

	DoubleLList_t* Phead;
	Phead=Head->next;

	if (Head==Head->next){
		Phead = New;
		Head->next=Phead;
		return true;
	}
	Phead->prev->next=New;
	New->prev=Phead->prev;
	New->next=Phead;
	Phead->prev=New;
	Head->next=New;
	return true;
}

//双向循环链表头删
bool deleteInCircularDoublyLinkedList(DoubleLList_t*Head)
{
	DoubleLList_t*Phead;
	Phead=Head->next;

	if (Head==Head->next){
		printf("链表为空\n");
		return true;
	}
	
	if (Phead->next!=Phead){

		Head->next=Phead->next;
		Phead->prev->next=Phead->next;
		Phead->next->prev=Phead->prev; //左值指向右值
	}else{
		Head->next=Head;
	}

	Phead->next=NULL;
	Phead->prev=NULL;

	free(Phead);
	return true;

}



posted @ 2024-05-06 22:49  晖_IL  阅读(4)  评论(0编辑  收藏  举报