如果让别人来决定你的人生,你的内心永远不会感到踏实!–拿破仑
1. DList.h
#pragma once
typedef int DLDataType; //双向循环链表结构体名称
typedef struct DListNode{
struct DListNode* _pNext; //指向当前结点的下一个
struct DListNode* _pPre;
DLDataType _data; //当前节点的值域
//结构体别名; struct DListNode的别名
}DLNode, *PDLNode;
void DListInit(PDLNode* pHead);
void DListPushBack(PDLNode pHead, DLDataType data);
void DListPopBack(PDLNode pHead);
void DListPushFront(PDLNode pHead, DLDataType data);
void DListPopFront(PDLNode pHead);
void DListInsert(PDLNode pos, DLDataType data);
void DListErase(PDLNode pos);
void DListClear(PDLNode pHead);
void DListDestroy(PDLNode* pHead);
void TestDList();
2.DList.c
#include "DList.h"
#include <malloc.h>
#include <assert.h>
#include <stdio.h>
//初始化
void DListInit(PDLNode* pHead){
assert(pHead);
*pHead = (PDLNode)malloc(sizeof(DLNode));
if (NULL == *pHead){
assert(0);
return;
}
(*pHead)->_pNext = *pHead;
(*pHead)->_pPre = *pHead;
}
//获取结点
PDLNode BuyDListNode(DLDataType data){
PDLNode pNewNode = (PDLNode)malloc(sizeof(DLNode));
if (NULL == pNewNode){
assert(0);
return;
}
pNewNode->_pNext = NULL;
pNewNode->_pPre = NULL;
}
//插入的原则:在不破坏链表结构的前提下进行操作
//尾插
void DListPushBack(PDLNode pHead, DLDataType data){
PDLNode pNewNode = BuyDListNode(data); //获取一个新结点
pNewNode->_pNext = pHead;
pNewNode->_pPre = pHead->_pPre;
pHead->_pPre->_pNext = pNewNode;
pHead->_pPre = pNewNode;
}
//尾删
void DListPopBack(PDLNode pHead){
assert(pHead);
if (pHead == pHead->_pNext){
return;
}
PDLNode pDelNode = pHead->_pPre;
pDelNode->_pPre->_pNext = pHead;
pHead->_pPre = pDelNode->_pPre;
free(pDelNode);
}
//头插
void DListPushFront(PDLNode pHead, DLDataType data){
PDLNode pNewNode = BuyDListNode(data);
pNewNode->_pNext = pHead->_pNext;
pNewNode->_pPre = pHead;
pHead->_pNext = pNewNode;
pNewNode->_pNext->_pPre = pNewNode;
}
//头删
void DListPopFront(PDLNode pHead){
assert(pHead);
if (pHead->_pNext == pHead){
return;
}
PDLNode pDelNode = pHead->_pNext;
pHead->_pNext = pDelNode->_pNext;
pDelNode->_pNext->_pPre = pHead;
free(pDelNode);
}
//任意插入
void DListInsert(PDLNode pos, DLDataType data){
if (NULL == pos){
return;
}
PDLNode pNewNode = BuyDListNode(data);
pNewNode->_pNext = pos;
pNewNode->_pPre = pos->_pPre;
pos->_pPre = pNewNode;
pNewNode->_pPre->_pNext = pNewNode;
}
//任意删除
void DListErase(PDLNode pos){
if (NULL == pos){
return;
}
pos->_pNext->_pPre = pos->_pPre;
pos->_pPre->_pNext = pos->_pNext;
free(pos);
}
//清空
void DListClear(PDLNode pHead){
PDLNode pCur = pHead->_pNext;
while (pCur != pHead){
pHead->_pNext = pCur->_pNext;
free(pCur);
pCur = pHead->_pNext;
}
pHead->_pNext = pHead;
pHead->_pPre = pHead;
}
//销毁
void DListDestroy(PDLNode* pHead){
DListClear(*pHead);
free(*pHead);
*pHead = NULL;
}
//测试
void TestDList(){
PDLNode pHead = NULL;
DListInit(&pHead);
}
3.test.c
int main(){
TestDList();
system("pause");
return 0;
}