题解 | #牛牛的单链表求和#
牛牛的单链表求和
https://www.nowcoder.com/practice/a674715b6b3845aca0d5009bc27380b5
#include <stdio.h> #include <stdlib.h> typedef struct ListNode { int val; struct ListNode *next; } ListNode; // 创建链表 ListNode* createLinkedList(int* arr, int n) { ListNode* head = NULL; ListNode* cur = NULL; for (int i = 0; i < n; ++i) { ListNode* node = (ListNode*)malloc(sizeof(ListNode)); node->val = arr[i]; node->next = NULL; if (head == NULL) { head = node; cur = node; } else { cur->next = node; cur = cur->next; } } return head; } // 遍历链表并求和 int sumLinkedList(ListNode* head) { int sum = 0; ListNode* cur = head; while (cur != NULL) { sum += cur->val; cur = cur->next; } return sum; } int main() { int n; scanf("%d", &n); int* arr = (int*)malloc(sizeof(int) * n); for (int i = 0; i < n; ++i) { scanf("%d", &arr[i]); } ListNode* head = createLinkedList(arr, n); int sum = sumLinkedList(head); printf("%d\n", sum); // 释放链表内存 ListNode* cur = head; while (cur != NULL) { ListNode* temp = cur; cur = cur->next; free(temp); } free(arr); return 0; }
这段代码首先定义了链表节点的结构体ListNode
,包括一个整数类型的值和一个指向下一个节点的指针。
接着定义了两个函数:
- createLinkedList函数用于创建链表,根据输入的数组创建一个链表,并返回链表的头节点指针。
- sumLinkedList函数用于遍历链表并求和,根据链表的头节点指针,遍历链表并累加每个节点的值,最后返回总和。
在主函数中,首先读入一个正整数n
,表示数组的长度。然后动态分配一个大小为n
的数组,并读入数组的元素值。
接下来调用createLinkedList
函数,将数组转换为链表,并返回链表的头节点指针。
然后调用sumLinkedList
函数,传入链表的头节点指针,计算链表上所有节点值的和。
最后输出求和的结果,并释放链表和数组的内存。
综上所述,这段代码可以实现将数组转换为链表,并计算链表上所有节点值的和。