删除链接列表中的节点通过引用传递给函数

时间:2014-04-08 16:10:46

标签: c linked-list

我想删除链接列表中的节点,但它没有按预期工作。我也不确定如何在某些时候释放被删除的节点。这是来源:

typedef struct Node {
    struct Node *next;
    //there are much more values here but just take this one for simplicity
    int value;
} Node;


void removeNode(Node **nH, Node **n, Node **nP){
    Node *current = (*n);
    Node *nodeHead = (*nH);
    Node *nodePrev = (*nP);
    if(nodeHead == current){
        puts("head element detected");
        if(current->next == NULL){
            free(current);
            current = NULL;
            nodeHead = NULL;
        } else{
            current = current->next;
        }
    } else {
        if (current->next == NULL){
            nodePrev->next = NULL;
            free(current);
            current = nodePrev;
        } else{
            current = current->next;
        }
    }
}

void validateNodes(Node **newNodes, Node **mainNodes){
    Node *newHead = (*newNodes);
    Node *newTmp = newHead;
    Node *newPrev = NULL;
    //validation of values here
    //for testing just remove the head element
    removeNode(&newHead, &newTmp, &newPrev);
}
void printAllNodes(Node *s){
    for(;;){
        printf("%d\n", s->value);
        if(s->next != NULL)
            s = s->next;
        else
            break;
    }   
}

int main(int argc, char **argv){
    //population of the nodes goes here
    //for now lets assume we have 3 nodes with the values [1, 2, 3]
    printAllNode(newSchedule);
    validateNodes(&newSchedule, &mainSchedule);
    printAllNode(newSchedule);
}

函数printAllNode只循环遍历节点并打印value。代码的输出如下:

1
2
3
head element detected
1
2
3

你可以看到没有任何东西消失。 我该如何解决这个问题?我非常不确定如何处理指针指针。

1 个答案:

答案 0 :(得分:0)

#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
    struct Node *next;
    int value;
} Node;

void removeNode(Node **nH, Node *n, Node *nP){
    if(*nH == n){
        if(nP)
            nP->next = (*nH)->next;
        else
            *nH = (*nH)->next;
        free(n);
    } else {
        if((*nH)->next)
            removeNode(&(*nH)->next, n, *nH);
    }
}

void validateNodes(Node **newNodes, Node **mainNodes){
    removeNode(newNodes, *newNodes, NULL);
}
void printAllNodes(Node *s){
    while(s){
        printf("%d\n", s->value);
        s = s->next;
    }
}

int main(int argc, char **argv){
    Node *newSchedule, *mainSchedule;
    Node **nodes = malloc(3 * sizeof(Node*));
    int i;
    for(i=0;i<3;++i)
        nodes[i]=malloc(sizeof(Node));
    for(i=0;i<3;++i){
        nodes[i]->value = i+1;
        nodes[i]->next = nodes[i+1];
    }
    nodes[2]->next = NULL;
    newSchedule = nodes[0];
    printAllNodes(newSchedule);
    validateNodes(&newSchedule, &mainSchedule);
    printf("\n");
    printAllNodes(newSchedule);
    //deallocate;
    return 0;
}