我在之前一篇博客《C語言實現非循環雙鏈表節點的刪除(不帶頭結點)》中詳細講解了不含頭尾節點的雙鏈表中刪除一個節點,處理過程還是稍顯麻煩。自從我們學習使用頭尾節點來處理雙鏈表後,刪除過程就非常方便。代碼上傳至 https://github.com/chenyufeng1991/DeleteNodeDoubleLinkedList_HeadList。
核心代碼如下:
//刪除pos位置的節點 int DeletePosList(Node *pHead,Node *pTail,int pos){ int i = 1; Node *pMove; pMove = pHead->next; while (pMove != pTail) { if (i == pos) { pMove->prior->next = pMove->next; pMove->next->prior = pMove->prior; free(pMove); pMove = NULL; printf("%s函數執行,刪除pos=%d位置的節點成功\n",__FUNCTION__,pos); return 1; } i++; pMove = pMove->next; } printf("%s函數執行,刪除pos=%d位置的節點失敗\n",__FUNCTION__,pos); return 0; } //刪除值為x的節點,若存在該節點則刪除之 int DeleteValueList(Node *pHead,Node *pTail,int x){ Node *pMove; pMove = pHead->next; while (pMove != pTail) { if (pMove->element == x) { pMove->prior->next = pMove->next; pMove->next->prior = pMove->prior; free(pMove); pMove = NULL; printf("%s函數執行,刪除值為x=%d的節點成功\n",__FUNCTION__,x); return 1; } pMove = pMove->next; } printf("%s函數執行,刪除值為x的節點失敗\n",__FUNCTION__); return 0; }