题解 | 牛牛的单链表求和
牛牛的单链表求和
https://www.nowcoder.com/practice/a674715b6b3845aca0d5009bc27380b5
#include <stdio.h>
#include <stdlib.h>
// write your code here......
struct node
{
int data;
struct node* next;
};
struct node* creat_list(int arr[],n)
{
struct node* list=(struct node*)malloc(sizeof(struct node));
if(list==NULL){
return NULL;
}
struct node* p=list;
for(int i=0;i<n;i++)
{
struct node* tep=(struct node*)malloc(sizeof(struct node));
p->next=tep;
p=p->next;
tep->data=arr[i];
}
p->next=NULL;
return list;
}
int main() {
int n;
scanf("%d",&n);
int* arr=(int*)malloc(n*sizeof(int));
for (int i = 0; i < n; i++) {
scanf("%d",&arr[i]);
}
// write your code here......
struct node* list=creat_list(arr,n);
int sum;
for(struct node*p=list->next;p;p=p->next)
{
sum=sum+p->data;
}
printf("%d",sum);
free(arr);
return 0;
}
