题解 | #牛牛的单链表求和#
牛牛的单链表求和
https://www.nowcoder.com/practice/a674715b6b3845aca0d5009bc27380b5
#include <stdio.h> #include <stdlib.h> typedef struct node { int num; struct node* next; } Node; Node* createlist(int num) { Node* head=(Node*)malloc(sizeof(Node)); head->num=num; head->next=NULL; return head; } void add_node(Node* head,int num) { Node* p=(Node*)malloc(sizeof(Node)); p->num=num; p->next=NULL; Node* q=head; while(q->next) { q=q->next; } q->next=p; } int sum_node(Node* head) { int res=0; Node *p=head; while(p) { res+=p->num; p=p->next; } return res; } int main() { int n; scanf("%d",&n); int t; scanf("%d",&t); Node* head=createlist(t); while(n--!=1) { scanf("%d",&t); add_node(head,t); } int res=sum_node(head); printf("%d\n",res); Node* p; while(head) { p=head; head=head->next; free(p); } return 0; }