题解 | #牛牛的单链表求和#
牛牛的单链表求和
https://www.nowcoder.com/practice/a674715b6b3845aca0d5009bc27380b5
#include <stdio.h> #include <stdlib.h> typedef int data_t ; typedef struct node{ data_t data; struct node *next; }listnode,*linklist; //链表创建 linklist list_create() { linklist H = (linklist)malloc(sizeof(listnode)); if(H == NULL) { printf("mallloc is failed"); return NULL; } H->data = 0; H->next = NULL; return H; } //链表插入 void list_insert(linklist H) { linklist L = (linklist)malloc(sizeof(listnode)); linklist h = H; if(L == NULL) { printf("mallloc is failed"); return ; } int value; scanf("%d",&value); while(h->next != NULL) { h = h->next; } h->next = L; L->data = value; L->next = NULL; return; } //链表求和 int list_sum(linklist H) { int sum = 0; linklist h = H->next; while (h->next != NULL) { sum+=h->data; h = h->next; } sum+=h->data; return sum; } int main() { int i, n,sum; linklist H = list_create(); scanf("%d",&n); for(i = 0;i<n;i++) list_insert(H); sum = list_sum(H); printf("%d\n",sum); return 0; }