题解 | #牛牛的单链表求和#
牛牛的单链表求和
https://www.nowcoder.com/practice/a674715b6b3845aca0d5009bc27380b5
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* pNext;
} NODE, *PNODE;
PNODE create_list();
void add_list(PNODE pHead);
int main() {
PNODE pHead = NULL;
pHead = create_list();
add_list(pHead);
return 0;
}
PNODE create_list() {
int n, val, i;
PNODE pHead = (PNODE)malloc(sizeof(NODE));
if (NULL == pHead) {
exit(-1);
}
PNODE p = pHead;
p->pNext = NULL;
scanf("%d", &n);
for (i = 0; i < n; i++) {
PNODE pNew = (PNODE)malloc(sizeof(NODE));
if (NULL == pNew) {
exit(-1);
}
scanf("%d", &val);
pNew->data = val;
pNew->pNext = NULL;
p->pNext = pNew;
p = pNew;
}
return pHead;
}
void add_list(PNODE pHead) {
int sum = 0;
PNODE p = pHead;
while (NULL != p->pNext) {
p = p->pNext;
sum += p->data;
}
printf("%d", sum);
}


查看1道真题和解析