题解 | #牛牛的单链表求和#

牛牛的单链表求和

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;
}

全部评论

相关推荐

09-13 08:41
服装/纺织设计
那一天的Java_J...:你第一次参加面试吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务