帶頭迴圈雙向連結串列的增刪查詢操作
阿新 • • 發佈:2018-11-30
#pragma once #include <assert.h> #include <stdlib.h> #include <stdio.h> //雙向帶頭迴圈 連結串列(如果要改變連結串列的頭指標指向,就要傳入二級指標) typedef int DataType; typedef struct DListNode { DataType data; struct DListNode *prev; struct DListNode *next; }DListNode; //初始化 銷燬 清空連結串列 插入節點 刪除節點 void DListInit(DListNode **ppHead, DataType data) { assert(ppHead); DListNode *pHead = (DListNode *)malloc(sizeof(DListNode)); pHead->data = data; assert(pHead != NULL); //初始化時,建立一個頭結點,有時候會讓頭結點的data存一些有效資訊(長度) pHead->next = pHead;//指向自己 pHead->prev = pHead;//指向自己 *ppHead = pHead; } // 銷燬連結串列 但是要保留頭結點 void DListClear(DListNode *pHead) { DListNode *cur = pHead->next; DListNode *next = NULL; while (cur != pHead) { next = cur->next; free(cur); cur = next; } pHead->next = pHead; pHead->prev = pHead; } // 銷燬連結串列 不保留頭結點 void DListDestroy(DListNode **ppHead) { assert(ppHead); DListClear(*ppHead); free(*ppHead); *ppHead = NULL; } DListNode* DListFind(DListNode *pHead, DataType data) { assert(pHead); DListNode *pcur = pHead->next; while (pcur != pHead) { if (pcur->data == data) { return pcur; } pcur = pcur->next; } printf("have no data!!!\n"); return NULL; } //插入(pos前面插入) void DListInsert(DListNode *pHead, DListNode *pos, DataType data) { assert(pHead); assert(pos); DListNode *newNode = (DListNode *)malloc(sizeof(DListNode)); newNode->data = data; newNode->prev = pos->prev; newNode->next = pos; pos->prev->next = newNode; pos->prev = newNode; } //刪除(刪除pos節點)(pos不能是頭節點) void DListErase(DListNode *pHead, DListNode *pos) { assert(pos != pHead); assert(pos != NULL); pos->prev->next = pos->next; pos->next->prev = pos->prev; free(pos); } void DListPrint(DListNode *pHead) { assert(pHead); DListNode *cur = pHead; while (cur->next != pHead) { printf("%d->", cur->data); cur = cur->next; } printf("%d->", cur->data); printf("%d\n", cur->next->data); } void Test() { DListNode *pHead = NULL;//頭節點指標 DListInit(&pHead, 0);//頭節點 DListInsert(pHead, pHead, 1); DListInsert(pHead, pHead, 2); DListInsert(pHead, pHead, 3); DListInsert(pHead, pHead, 4); DListInsert(pHead, pHead, 5); DListErase(pHead, DListFind(pHead, 1));//頭刪 DListErase(pHead, DListFind(pHead, 2)); DListErase(pHead, DListFind(pHead, 3));//任意位置刪除 DListErase(pHead, DListFind(pHead, 4)); DListErase(pHead, DListFind(pHead, 5));//尾刪 DListPrint(pHead); DListDestroy(&pHead); }