root之后的链表删除节点

时间:2016-04-28 19:16:39

标签: c linked-list

我正在链接列表上练习,我遇到了一个问题。链表是一个尾部,所以我想删除位于根节点上方的第一个元素。我想要在任何情况下删除根节点。代码是:

struct goods {
    char* section;
    char* pname;
    int value;
    int customer_num;
    int cash;
    struct goods* next;
};

void delete_goods(int customer_num, struct goods* root) {
    struct goods *current = root;
    struct goods *previous = NULL;
    while (current != NULL) {
        if (current->customer_num == customer_num) {
            if (previous == NULL) {
                current = current->next;
                free(root);
            } else {
                previous->next = current->next;
                free(current);
                current = previous->next;
            }
        } else {
            previous = current;
            current = current->next;
        }
    }
}

int main() {
    root = malloc(sizeof(struct goods));
    root->next = NULL;
    printf("give the number of starting customers\n");
    scanf("%d", &customers);
    inform_list(customers);     // adds element to list



    else if (r == 'r' && customers != 0) {
        printf("removing...\n");
        delete_goods(customers, root);
        customers -= 1;
        printf("customers:\t%d\n", customers);
        print();
    }
}

我没有发布整个代码(它包含一些函数,用于为方便起见添加元素到链接列表)如果你愿意,我可以这样做。我需要修复我的删除功能,以满足我的需求综上所述。 这里是列表的示例输出:
customers: 2 customer: 2 item value: 32 product name: asdasd customer: 1 item value: 43 product name: sdsad customer: 0 item value: 0 product name: (null) 我需要的是我的删除功能,如果被问到客户2等,则删除客户1。

1 个答案:

答案 0 :(得分:1)

正如其他人所提到的,您希望保留根节点,因此您希望从root->next开始(即root始终为非空)。

这应该有效[请原谅无偿的风格清理]:

void
delete_goods(int customer_num, struct goods *root)
{
    struct goods *current = root->next;
    struct goods *previous = NULL;
    struct goods *next;

    for (;  current != NULL;  current = next) {
        next = current->next;

        if (current->customer_num == customer_num) {
            if (previous != NULL)
                previous->next = next;
            else
                root->next = next;

            free(current);
        }
        else
            previous = current;
    }
}

这是一个稍微紧凑的版本:

void
delete_goods(int customer_num, struct goods *root)
{
    struct goods *current = root->next;
    struct goods *previous = root;
    struct goods *next;

    for (;  current != NULL;  current = next) {
        next = current->next;

        if (current->customer_num == customer_num) {
            previous->next = next;
            free(current);
        }
        else
            previous = current;
    }
}