题解 | #牛牛的单链表求和#
牛牛的单链表求和
https://www.nowcoder.com/practice/a674715b6b3845aca0d5009bc27380b5
#include <stdio.h> #include <stdlib.h> struct ListNode { int val; struct ListNode* next; }; struct ListNode* createLinkedList(int arr[], int n) { if (n == 0) { return NULL; } struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode)); head->val = arr[0]; head->next = NULL; struct ListNode* curr = head; for (int i = 1; i < n; i++) { curr->next = (struct ListNode*)malloc(sizeof(struct ListNode)); curr->next->val = arr[i]; curr->next->next = NULL; curr = curr->next; } return head; } int sumLinkedList(struct ListNode* head) { int sum = 0; struct ListNode* curr = head; while (curr != NULL) { sum += curr->val; curr = curr->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]); } struct ListNode* head = createLinkedList(arr, n); int sum = sumLinkedList(head); printf("%d\n", sum); free(arr); struct ListNode* curr = head; struct ListNode* next = NULL; while (curr != NULL) { next = curr->next; free(curr); curr = next; } return 0; }