1. 程式人生 > >C語言實現單鏈表節點的刪除(帶頭結點)

C語言實現單鏈表節點的刪除(帶頭結點)

data art pos grand urn ria tps move sni

我在之前一篇博客《C語言實現單鏈表節點的刪除(不帶頭結點)》中具體實現了怎樣在一個不帶頭結點的單鏈表的刪除一個節點,在這一篇博客中我改成了帶頭結點的單鏈表。代碼演示樣例上傳至 https://github.com/chenyufeng1991/DeleteLinkedList_HeadNode。刪除類型有兩種:

(1)刪除某個位置pos的節點;

(2)推斷x值是否在鏈表中,若存在則刪除該節點;

核心代碼例如以下:

//刪除某個位置pos的節點
Node *DeletePosNode(Node *pNode,int pos){

    int i = 1;
    Node *pMove;
    Node *pMovePre;
    pMovePre = pNode;
    pMove = pNode->next;
    while (pMove != NULL) {
        if (i == pos) {

            pMovePre->next = pMove->next;
            free(pMove);
            pMove = NULL;
            printf("%s函數運行。在pos=%d位置刪除節點成功\n",__FUNCTION__,pos);
            return pNode;
        }
        i++;
        pMovePre = pMovePre->next;
        pMove = pMove->next;
    }

    printf("%s函數運行,在pos=%d位置刪除節點失敗\n",__FUNCTION__,pos);

    return pNode;
}

//推斷x值是否在鏈表中,若存在則刪除該節點
Node *DeleteValueNode(Node *pNode,int x){


    Node *pMovePre;
    Node *pMove;
    pMovePre = pNode;
    pMove = pNode->next;
    while (pMove != NULL) {
        if (pMove->element == x) {
            pMovePre->next = pMove->next;
            free(pMove);
            pMove = NULL;

            printf("%s函數運行,刪除value=%d節點成功\n",__FUNCTION__,x);
            return pNode;
        }
        pMovePre = pMovePre->next;
        pMove = pMove->next;
    }

    printf("%s函數運行,刪除value=%d節點失敗\n",__FUNCTION__,x);

    return pNode;
}


C語言實現單鏈表節點的刪除(帶頭結點)