带头节点的双向循环链表

链表分为单向链表和双向链表,前两篇都是关于单向链表的函数,这篇是有关双向循环链表的函数,

首先,我们我要知道双向循环链表长什么样子

这里写图片描述

双向循环链表结构体:

typedef int DataType;

typedef struct DListNode {
    struct DListNode* _pNext;
    struct DListNode* _pPre;
    DataType _data;

}DListNode;

函数:

DListNode* BuyDListNode(DataType data)//创建节点
{
    DListNode* pNewNode = (DListNode*)malloc(sizeof(DListNode));
    if (NULL == pNewNode)
    {
        assert(0);
        return NULL;
    }
    pNewNode->_pNext = NULL;
    pNewNode->_pPre = NULL;
    pNewNode->_data = data;
}

void DListInit(DListNode** pHead)//初始化//输出型参数
{
    assert(pHead);
    *pHead = BuyDListNode(0);
    (*pHead)->_pNext = (*pHead);
    (*pHead)->_pPre = (*pHead);
}

void DListPushBack(DListNode* pHead,DataType data)//尾部插入
{
    DListNode* pNewNode = NULL;
    assert(pHead);
    pNewNode = BuyDListNode(data);
    //尾插
    pNewNode->_pPre = pHead->_pPre;
    pNewNode->_pNext = pHead;
    pNewNode->_pPre->_pNext = pNewNode;
    pHead->_pPre = pNewNode;

}
void DListPopBack(DListNode* pHead)//尾部删除
{
    DListNode* pDelNode = NULL;
    assert(pHead);
    pDelNode = pHead->_pPre;
    if (pDelNode != pHead)
    {
        pDelNode->_pPre->_pNext = pDelNode->_pNext;
        pDelNode->_pNext->_pPre = pDelNode->_pPre;
        free(pDelNode);
    }
}


DListNode* DListFind(DListNode* pHead,DataType data)//查找节点
{
    DListNode* pCur;
    assert(pHead);
    pCur = pHead->_pNext;
    while (pCur != pHead)
    {
        if (data == pCur->_data)
            return pCur;
        pCur = pCur->_pNext;
    }
    return NULL;

}

void DListInsert(DListNode* pos, DataType data)//插到pos前面
{
    DListNode* pNewNode = NULL;
    //assert(pos);
    if (NULL == pos)
        return;
    pNewNode = BuyDListNode(data);
    pNewNode->_pNext = pos;
    pNewNode->_pPre = pos->_pPre;
    pos->_pPre = pNewNode;
    pNewNode->_pPre->_pNext = pNewNode;
}
void DListErase(DListNode* pos)//删除pos节点
{
    if (NULL == pos)
        return;
    pos->_pPre->_pNext = pos->_pNext;
    pos->_pNext->_pPre = pos->_pPre;
    free(pos);
}

有问题的欢迎留言,

猜你喜欢

转载自blog.csdn.net/qq_39032310/article/details/81735251