题解 | #牛牛的单链表求和#
牛牛的单链表求和
https://www.nowcoder.com/practice/a674715b6b3845aca0d5009bc27380b5
#include <stdio.h> #include <stdlib.h> typedef struct Node { int data; struct Node* next; }Node; // 链表初始化 Node* initList() { Node* list = (Node*)malloc(sizeof(Node)); list->next = NULL; list->data = 0; return list; } // 尾插法 void tailInsert(Node* list, int data) { Node* node = (Node*)malloc(sizeof(Node)); node->data = data; node->next = NULL; Node* head = list; // 指针移动到第一个节点的位置 while (head->next != NULL) { head = head->next; } head->next = node; list->data ++ ; } // 链表元素求和 int getSum(Node* list) { int sum = 0; Node* head = list->next; while (head) { sum += head->data; head = head->next; } return sum; } int main() { int n; scanf("%d", &n); Node* list = initList(); for (int i = 0; i < n; i ++ ) { int x; scanf("%d", &x); tailInsert(list, x); } printf("%d", getSum(list)); return 0; }