题解 | #牛牛的单链表求和#
牛牛的单链表求和
https://www.nowcoder.com/practice/a674715b6b3845aca0d5009bc27380b5
#include <stdio.h>
typedef struct node{
int data;
struct node *next;
}node;
int sum_node(node *head);
void printf_node(node *head);
void add_node(node *head,int data);
node *cteat_node();
int main() {
int n;
node *head=cteat_node();
scanf("%d ",&n);
while (scanf("%d ", &n) != EOF) { // 注意 while 处理多个 case
add_node(head,n);
}
printf("%d ",sum_node(head));
return 0;
}
//创建头链表
//返回值为链表表头
//链表头默认data=0;
//链表尾->next = NULL
node *cteat_node(){
node *head=(node *)malloc(sizeof(node));
head->next=NULL;
return head;
}
//尾插添加
// head为链表头 data为数据
void add_node(node *head,int data){
node *pT=NULL;
node *new=(node *)malloc(sizeof(node));
new->data=data;
for(pT=head;pT->next!=NULL;pT=pT->next){};//表尾->next为NULL
pT->next=new;//链接
}
//打印链表
//head为表头
void printf_node(node *head){
for(node *pT=head;pT!=NULL;pT=pT->next){
if(pT!=head)printf("%d ",pT->data);
}
}
//函数功能:求和
//函数参数:head 表头
//函数返回值:int sum
int sum_node(node *head){
int sum=0;//求和值sum
for(node *pT= head;pT != NULL; pT= pT->next ){
sum+=pT->data;
}//循环到pT=NULL sum累加
return sum;
}

CVTE公司福利 672人发布