双向循环链表:
1.首先,双向链表通常采用带表头结点的循环链表形式,即双向循环链表。双向循环链表在双向链表的基础上,将表头结点的前驱指针指向尾结点,尾结点的后驱指针指向头结点,首尾相连形成一个双向环。双向循环链表可方便地获取当前结点的前驱结点,不必像单向循环链表那样从头开始遍历;而其循环的特性又可方便地从任一结点出发单向遍历整个链表,不必像双向链表那样根据方向而使用不同的指针域。
2.如图所示:
3.代码如下:
#include"stdio.h"
#include"stdlib.h"
#include"assert.h"
#pragma warning (disable:4996)
typedef int DataType;
typedef struct DCLNode
{
struct DCLNode* _pNext;
struct DCLNode* _pPre;
DataType _data;
}Node, *PNode;
//初始化双向循环列表
void DCLInit(PNode* ppHead)
{
assert(ppHead);
*ppHead = (PNode)malloc(sizeof(Node));
if (NULL == *ppHead)
assert(0);
(*ppHead)->_pNext = *ppHead;
(*ppHead)->_pPre = *ppHead;
}
//构造一个新结点
PNode DCLBuyNode(DataType data)
{
PNode pNewNode = (PNode)malloc(sizeof(Node));
if (NULL == PNewNode)
assert(0);
pNewNode->_data = data;
pNewNode->_pNext = NULL;
pNewNode->_pPre = NULL;
return pNewNode;
}
//尾插
void DCLPushBack(PNode pHead, DataType data)
{
PNode DCLBuyNode(data);
PNode pTailNode = NULL;
assert(pHead);
pTailNode = pHead->_pPre;
pTailNode->_pNext = pNewNode;
pNewNode->_pPre = pTailNode;
pNewNode->_pNext = pHead;
pHead->_pPre = pTailNode;
}
//尾删
void DCLPopBack(PNode pHead)
{
if (pHead->_pNext == pHead)
{
return;
}
else
{
PNode pPreTail = pHead->_pPre->_pPre;
free(pPreTail->_pNext);
pPreTail->_pNext = pHead;
pHead->_pPre = pPreTail;
}
}
//头插
void DCLPushFront(PNode pHead, DataType data)
{
PNode pNewNode = DCLBuyNode(data);
assert(pHead);
pNewNode->_pNext = pHead->_pNext;
pHead->_pNext->_pPre = pNewNode;
pNewNode->_pPre = pHead;
pHead->_pNext = pNewNode;
}
//头删
void DCLPopFront(PNode pHead)
{
if (pHead->_pNext == pHead)
{
return;
}
else
{
PNode pDel = pHead->_pNext;
pHead->_pNext = pDel->_pNext;
pDel->_pNext->_pPre = pHead;
free(pDel);
}
}
//打印
void DCLPrintList(PNode pHead)
{
pNode pCur = NULL;
assert(pHead);
pCur = pHead->_pNext;
while (pCur != pHead)
{
printf("%d->",pCur->_data);
}
printf("\n");
}
//任意位置删除
void DCLInsert(PNode pos, DataType data)
{
PNode pNewNode = DCLBuyNode(data);
assert(pNewNode);
pNewNode->_pNext = pos;
pos->_pPre->_pNext = pNewNode;
pNewNode->_pPre = pos->_pPre;
pos->_pPre = pNewNode;
}
//任意位置删除
void DCLErase(PNode pos)
{
pos->_pPre->_pNext = pos->_pNext;
pos->_pNext->_pPre = pos->_pPre;
free(pos);
}
//查找元素
PNode DCLFind(PNode pHead, DataType data)
{
PNode pCur = pHead->_pNext;
while (pCur != pHead)
{
if (pCur->_data == data)
{
return pCur;
}
pCur = pCur->_pNext;
}
return NULL;
}
//销毁链表
void DCLDestroy(PNode* ppHead)
{
PNode pCur = NULL;
assert(ppHead);
pCur = (*ppHead)->_pNext;
while (pCur != *ppHead)
{
pCur = pCur->_pNext;
free(pCur->_pPre);
}
free(pCur);
*ppHead = NULL;
}