Bootstrap

三、双链表

在这里插入图片描述
链表的种类有很多,单链表是不带头不循环单向链表,但双链表是带头循环双向链表,并且双链表还有一个哨兵位,哨兵位不是头节点

 typedef int LTDataType;
 typedef struct ListNode
 {
  struct ListNode* next; //指针保存下⼀个结点的地址
  struct ListNode* prev; //指针保存前⼀个结点的地址
  LTDataType data;
 }LTNode;
//创建链表,创建关于x的链表
LTNode* buyNode(LTDataType x) {
	LTNode* node = (LTNode*)malloc(sizeof(LTNode));
	if (node == NULL) {
		perror("open fail!");
		exit(1);
	}
	node->data = x;
	node->next = node->prev = node;
	return node;
}

//创建哨兵位
LTNode* LTInit()
{
	LTNode* phead = buyNode(-1);
	return phead;
}

//打印双链表
void LTPrint(LTNode* phead) {
	LTNode* node = phead->next;
	while (node!=phead) {
		printf("%d ", node->data);
		node = node->next;
	}
	printf("\n");
}

//尾插
void LTPushBack(LTNode* phead, LTDataType x) {
	assert(phead);
	LTNode* node = buyNode(x);
	node->next = phead;
	node->prev = phead->prev;
	phead->prev->next = node;
	phead->prev = node;
}

//头插
void LTPushFront(LTNode* phead, LTDataType x) {
	assert(phead);
	LTNode* newnode = buyNode(x);
	newnode->prev = phead;
	newnode->next = phead->next;

	phead->next->prev = newnode;
	phead->next = newnode;
}

//判空
bool LTEmpty(LTNode* phead)
{
	assert(phead);
	return phead->next == phead;
}

尾删
void LTPopBack(LTNode* phead) {
	assert(!LTEmpty(phead));
	LTNode* del = phead->prev;
	del->prev->next = phead;
	phead->prev = del->prev;
	free(del);
	del = NULL;
}


//头删
void LTPopFront(LTNode* phead) {
	assert(!LTEmpty(phead));
	LTNode* del = phead->next;
	del->next->prev = phead;
	phead->next = del->next;
	free(del);
	del = NULL;
}


//查询节点
LTNode* LTFind(LTNode* phead, LTDataType x) {
	assert(phead);
	LTNode* pcur = phead->next;
	while (pcur != phead)
	{
		if (pcur->data == x)
		{
			return pcur;
		}
		pcur = pcur->next;
	}
	return NULL;
}

//在pos位置之后插⼊数据
void LTInsert(LTNode* pos, LTDataType x) {
	assert(pos);
	LTNode* node = buyNode(x);
	LTNode* del = pos->next;
	node->next = del;
	node->prev = pos;
	pos->next = node;
	del->prev = node;
}

//删除pos位置的结点
void LTErase(LTNode* pos)
{
	assert(pos);
	pos->next->prev = pos->prev;
	pos->prev->next = pos->next;
	free(pos);
	pos = NULL;
}

//销毁链表
void LTDesTroy(LTNode* phead)
{
	LTNode* pcur = phead->next;
	while (pcur != phead)
	{
		LTNode* next = pcur->next;
		free(pcur);
		pcur = next;
	}
	free(phead);
	phead = NULL;
}
;