题解 | #牛牛的单链表求和#
牛牛的单链表求和
https://www.nowcoder.com/practice/a674715b6b3845aca0d5009bc27380b5
#include<stdio.h> #include<stdlib.h> typedef struct ListNode{ int value; struct ListNode*next; }ListNode; ListNode*creatNode(int value) { ListNode*newnode = (ListNode*)malloc(sizeof(ListNode)); newnode->value = value; newnode->next = NULL; return newnode; } ListNode*creatlist(int*array,int n) { if(n==0) return NULL; ListNode*head = creatNode(array[0]); ListNode*current = head; for(int i = 1;i<n;i++) { current->next = creatNode(array[i]); current = current->next; } return head; } int listsum(ListNode*head) { int sum = 0; ListNode*current = head; while(current!=NULL) { sum+=current->value; current = current->next; } return sum; } int main() { int n; scanf("%d ",&n); int*array=(int*)malloc(n*sizeof(int)); for(int i = 0;i<n;i++) { scanf("%d",&array[i]); } ListNode*head = creatlist(array,n); printf("%d\n",listsum(head)); while(head!=NULL) { ListNode*temp = head; head = head->next; free(temp); } free(array); return 0; }