面试题答案
一键面试#include <stdio.h>
#include <stdlib.h>
struct Node {
int value;
struct Node *next;
struct SubNode {
int subValue;
struct SubNode *subNext;
} *subHead;
};
// 递归计算SubNode链表中subValue的总和
int sumSubNode(struct Node::SubNode *subHead) {
if (subHead == NULL) {
return 0;
}
return subHead->subValue + sumSubNode(subHead->subNext);
}
// 递归计算Node数组及其嵌套链表中所有value和subValue的总和
int sumAll(struct Node *head) {
if (head == NULL) {
return 0;
}
int subSum = sumSubNode(head->subHead);
return head->value + subSum + sumAll(head->next);
}
你可以这样调用函数:
int main() {
// 这里省略构建链表的代码
struct Node *head = NULL;
int totalSum = sumAll(head);
printf("所有value和subValue的总和: %d\n", totalSum);
return 0;
}