gpt4 book ai didi

c - 链表删除root之后的节点

转载 作者:行者123 更新时间:2023-11-30 15:09:02 25 4
gpt4 key购买 nike

我正在做链表练习,遇到了一个问题。链表是尾部,所以我想删除根节点上方第一个元素。无论如何,我不想删除根节点。代码是:

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
客户:2
元素值(value):32
产品名称:阿斯达
客户:1
元素值(value):43
产品名称: sdsad
客户:0
元素值(value):0
产品名称:(无)
我需要的是我的删除功能,如果需要的话删除客户 1,然后删除客户 2 等。

最佳答案

正如其他人提到的,您希望保留根节点,因此您希望从 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;
}
}

关于c - 链表删除root之后的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36923623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com