题解 | #牛牛的单链表求和#
牛牛的单链表求和
https://www.nowcoder.com/practice/a674715b6b3845aca0d5009bc27380b5
#include <stdio.h> #include <stdlib.h> //声明结构体 struct List { int date; struct List* next; }; //新节点 struct List* BuyNewCode(int x) { struct List* new=(struct List*)malloc(sizeof(struct List)); new->date=x; new->next=NULL; return new; } //尾插(不带头) void PushBack(struct List** pplist,int x) { struct List* new=BuyNewCode(x); if(*pplist==NULL) { *pplist=new; } else { //用于寻找尾节点的指针 struct List* tail=*pplist; while(tail->next!=NULL) { tail=tail->next; } //找到,链接新节点 tail->next=new; } } //求和 int Sum(struct List* plist) { struct List* cur=plist; int sum=0; while(cur!=NULL) { sum+=cur->date; cur=cur->next; } return sum; } int main() { int n=0; scanf("%d",&n); //不带头指针的链表 struct List* plist=(struct List*)malloc(sizeof(struct List)); plist=NULL; int i=0; int k=0; for(i=0;i<n;i++) { scanf("%d",&k); PushBack(&plist,k); } int ret=Sum(plist); printf("%d\n",ret); return 0; }