5.实现一个函数可以求出列表中元素最大值
// 函数定义
ElementType Max(ElementType S[], int N) {
// 假设数组至少有一个元素
ElementType max = S[0];
for (int i = 1; i < N; i++) {
// 如果当前元素大于max,则更新max
if (S[i] > max) {
max = S[i];
}
}
// 返回最大值
return max;
}
这种求最大值、最小值的不要直接本着去实现一个排序算法去,如上所示例的直接遍历整个列表,不断更新max值会更好。
6.对一个单链表的每个结点计算阶乘并求和
int FactorialSum( List L ){
//遍历单链表
int i;
int temp;
int sum;
for(i=0;i<L.length;i++){
//求每个结点的阶乘
temp=mul(L[i])];
//对阶乘结果求和
sum+=temp;
}
}
int mul(L[]){
int mul=1;
for(i=0;i<=L[];i++){
mul*=i;
}
return mul;
}
#include <stdio.h>
// 阶乘函数
int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
// 计算链表结点阶乘和的函数
int FactorialSum(List L) {
int sum = 0;
ListNode *current = L;
// 遍历链表
while (current != NULL) {
// 计算当前结点的阶乘并累加到sum中
sum += factorial(current->value);
// 移动到下一个结点