``
双向链表也叫双链表,是链表的一种,它的每个数据结点中都有两个指针,分别指向直接后继和直接前驱。
带头双向循环链表是在双向循环链表的基础上,引用一个哨兵位的头结点,哨兵位无任何意义,
本次我们来实现带头双向循环链表的增删查改
链表的创建
链表增删查改的声明
LTNode* BuyLTNode(LTDataType x)
{
LTNode* newnode = (LTNode*)malloc(sizeof(LTNode));
if (newnode == NULL)
{
perror("malloc fail");
return NULL;
}
newnode->data = x;
newnode->next = NULL;
newnode->prev = NULL;
return newnode;
}
链表初始化就是定义哨兵位头结点,此处phead的data值可以为任意值
LTNode* LTInit()
{
LTNode* phead = BuyLTNode(-1);
phead->next = phead;
phead->prev = phead;
return phead;
}
在进行尾插时,最重要的一点时找到链表的尾端,又正因为时循环链表,所以链表的位段就是 phead->prev,在进行链表的链接
void LTPushBack(LTNode* phead, LTDataType x)
{
assert(phead);
LTNode* tail = phead->prev;
LTNode* newnode = BuyLTNode(x);
tail->next = newnode;
newnode->prev = tail;
newnode->next = phead;
phead->prev = newnode;
}
而在进行头插时,应该注意链表链接时的顺序,或者先标记好哨兵位的后继结点
void LTPushFront(LTNode* phead, LTDataType x)
{
assert(phead);
LTNode* newnode = BuyLTNode(x);
LTNode* first = phead->next;
newnode->next = first;
first->prev = newnode;
newnode->prev = phead;
phead->next = newnode;
}
本环节应该考虑循环多久停止,所以在循环链表中通常以phead->next为第一个结点开始遍历,当它回到phead时停止
void LTPrint(LTNode* phead)
{
assert(phead);
LTNode* cur = phead->next;
printf("guard<=>");
while (cur != phead)
{
printf("%d<=>", cur->data);
cur = cur->next;
}
printf("\n");
}
找到尾端与尾端的前驱结点,直接将head与tailPrev链接起来,最后释放tail
void LTPopBack(LTNode* phead)
{
assert(phead);
assert(!LTEmpty(phead));
LTNode* tail = phead->prev;
LTNode* tailPrev = tail->prev;
free(tail);
tailPrev->next = phead;
phead->prev = tailPrev;
}
定位到链表的第一个结点(不包括哨兵位),再进行头部的删除
void LTPopFront(LTNode* phead)
{
assert(phead);
assert(!LTEmpty(phead));
LTNode* next = phead->next;
phead->next = next->next;
next->next->prev = phead;
free(next);
}
在对链表进行删除时,我们必须考虑链表是否为空,对空链表的删除实则是个错误
bool LTEmpty(LTNode* phead)
{
assert(phead);
return phead->next == phead;
}
链表的查找实则为遍历一遍链表,找到符合的结点,同样要考虑循环结束的标志
LTNode* LTFind(LTNode* phead, LTDataType x)
{
assert(phead);
LTNode* cur = phead->next;
while (cur!=phead)
{
if (cur->data == x)
{
return cur;
}
cur = cur->next;
}
return NULL;
}
只需找到并记录pos的前驱结点,再进行链接即可
void LTInsert(LTNode* pos, LTDataType x)
{
assert(pos);
LTNode* prev = pos->prev;
LTNode* newnode = BuyLTNode(x);
//prev newnode pos
prev->next = newnode;
newnode->prev = prev;
newnode->next = pos;
pos->prev = newnode;
}
删除pos位置的值,需找到前驱结点和后继结点,并进行链接
void LTDelete(LTNode* pos)
{
assert(pos);
LTNode* posPrev = pos->prev;
LTNode* posNext = pos->next;
//posPrev pos posTail
posPrev->next = posNext;
posNext->prev = posPrev;
free(pos);
}
此处释放后形参并不能改变实参,所以需在主函数中将链表置空
void LTDestory(LTNode* phead)
{
assert(phead);
LTNode* cur = phead->next;
while (cur != phead)
{
LTNode* next = cur->next;
free(cur);
cur = next;
}
free(phead);
}