gpt4 book ai didi

c - 删除头节点和递归列表平均值

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

我正在处理一个链接列表,我必须使用递归函数找到其元素的平均值。但是,我的两个功能遇到问题:

1-如果我删除第一个节点,然后尝试检查内容,列表会喷出垃圾数据,如果我再次在列表前面插入某些内容,它只会无休止地重复显示第一个节点内容。

2-我似乎无法弄清楚如何使递归平均函数发挥作用。

以下是两者的代码片段:

void deletefront(head h) {
head temp; // create a temporary node.
temp = (head)malloc(sizeof(struct node)); // allocate space for node.
temp = h; // transfer the address of 'head' to 'temp'
h = temp->next; // transfer the address of 'temp->next' to 'head'
free(temp);
}


double average2(head h, int sum, int quantity, double avg) {
head temp3;
temp3 = (head)malloc(sizeof(struct node));
temp3 = h;
if (temp3 == NULL) {
cout << "List is Empty" << endl;
return 0;
}
else {
sum = sum + temp3->data;
quantity = quantity + 1;
temp3 = temp3->next;
if (temp3 == NULL) {
return avg = sum / quantity;
}
else return avg = average2(h, sum, quantity, avg);
}
}

这是标题:

typedef struct node
{
int data; // will store information
node *next; // the reference to the next node
}*head;

请注意,我必须确保这些函数可以适用于任何列表。

最佳答案

deletefront()你应该返回新的头,即head->next

head deletefront(head h) {
head temp; // create a temporary node

temp = h; // transfer the address of 'head' to 'temp'
h = temp->next; // transfer the address of 'temp->next' to 'head'
return h;
}

并且您应该将返回值设置为列表的头部。您的函数只是删除函数中的节点,此函数中的 h 值不会更改。

此外,您不需要 malloc() 来获取临时值。

<小时/>

对于第二个问题,将递归调用更新为

else return avg = average2(temp3, sum, quantity, avg);
//-------------------------^ don't use h

关于c - 删除头节点和递归列表平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30434854/

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