题解 | #牛牛的单链表求和#
牛牛的单链表求和
https://www.nowcoder.com/practice/a674715b6b3845aca0d5009bc27380b5
#include <stdio.h> #include <stdlib.h> typedef struct node{ int data; struct node *next; }node; node *arrayToLinkedList(int arr[], int n) { if (n == 0) { return NULL; } node *head = malloc(sizeof(node)); head->data = arr[0]; //第一个节点; head->next = NULL; //指针域为NULL; node *current = head;//流指针 for (int i = 1; i < n; i++) { //尾插法 node *newNode = malloc(sizeof(node)); newNode->data = arr[i];//创建新节点 newNode->next = NULL; current->next = newNode; current = newNode;//流指针向后移动 } return head; } //遍历链表并求和节点值 int sumLinkedList(node *head) { int sum = 0; node *current = head; //指针指向头节点 while (current != NULL) { sum = sum + current->data;//遍历节点的数据域相加; current = current->next; //流指针向后移动类似于p++; } return sum; //返回所有节点相加之和 } void freeLinkedList(node *head) { node *temp; while (head != NULL) { temp = head; head = head->next; //头指针向后移动 free(temp); //释放当前节点 } } int main() { int n; scanf("%d", &n); int arr[n]; for (int i = 0; i < n; i++) { scanf("%d", &arr[i]); } node *head = arrayToLinkedList(arr, n); int sum = sumLinkedList(head); printf("%d\n", sum); freeLinkedList(head); return 0; }