(10)已知f为单链表的表头指针,链表中存储的都是整型数据,试写出实现下列运算的递归算法 ①求链表中的最大整数;②求链表的结点个数;③求所有整数的平均值。
时间: 2023-06-02 14:07:21 浏览: 100
①递归求链表中的最大整数:
int getMax(Node* head){
if(head == NULL){
return INT_MIN;
}
int max_num = head->data;
int next_max = getMax(head->next);
return max(max_num, next_max);
}
调用方法: getMax(f)
②递归求链表的结点个数:
int getCount(Node* head){
if(head == NULL){
return 0;
}
return 1 + getCount(head->next);
}
调用方法: getCount(f)
③递归求所有整数的平均值:
double getAverage(Node* head){
if(head == NULL){
return 0.0;
}
int sum = head->data;
int count = 1;
double next_average = getAverage(head->next);
count += next_count;
sum += next_sum;
return (double)sum / count;
}
调用方法: getAverage(f)
相关问题
C语言(10)已知f为单链表的表头指针,链表中存储的都是整型数据,试写出实现下列运算的递归算法 ①求链表中的最大整数;②求链表的结点个数;③求所有整数的平均值。
好的,我可以回答这个问题。
①求链表中的最大整数的递归算法:
```
int getMax(ListNode* p) {
if (p == NULL) {
return INT_MIN; // 如果链表为空,则返回最小整数
} else {
int maxVal = getMax(p->next); // 递归找到后面节点的最大值
return max(maxVal, p->val); // 返回当前节点值和后面节点最大值之中的最大值
}
}
```
②求链表的结点个数的递归算法:
```
int getCount(ListNode* p) {
if (p == NULL) {
return 0; // 如果链表为空,则节点个数为0
} else {
return 1 + getCount(p->next); // 递归统计后面节点的个数,然后加上当前节点
}
}
```
③求所有整数的平均值的递归算法:
```
double getAverage(ListNode* p, int& count) {
if (p == NULL) {
return 0.0; // 如果链表为空,则平均值为0
} else {
double avg = getAverage(p->next, count); // 递归计算后面节点的平均值和节点个数
count++; // 节点个数加1
return ((avg * (count - 1)) + p->val) / count; // 累加当前节点值并更新平均值
}
}
```
希望可以帮助到您。
已知f为单链表的表头指针, 链表中存储的都是整型数据,试写出实现下列运算的递归算法: ① 求链表中的最大整数; ② 求链表的结点个数; ③ 求所有整数的平均值。
好的,我明白了。以下是你要求的递归算法:
① 求链表中的最大整数:
```
int getMax(ListNode* head) {
if (head == NULL) {
return INT_MIN;
}
int currMax = head->val;
int restMax = getMax(head->next);
return max(currMax, restMax);
}
```
② 求链表的结点个数:
```
int getCount(ListNode* head) {
if (head == NULL) {
return 0;
}
return 1 + getCount(head->next);
}
```
③ 求所有整数的平均值:
```
double getAverage(ListNode* head, int sum, int count) {
if (head == NULL) {
return (double)sum / count;
}
sum += head->val;
count++;
return getAverage(head->next, sum, count);
}
```
请注意,以上算法是基于单链表的。如果你的链表不是单链表,或是存储其他类型的数据(不是整型),上述算法需要做相应的修改。