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

牛牛的单链表求和

https://www.nowcoder.com/practice/a674715b6b3845aca0d5009bc27380b5

#include <stdio.h>
#include <stdlib.h>

typedef struct Node{
    int num;
    struct Node* next;
}NodeList;

NodeList* Init(){
    NodeList *p;
    p=(NodeList*)malloc(sizeof(NodeList));
    p->next=NULL;
    return p;
}

void CreateList(NodeList* head,int num){
    NodeList* p;
    for(int i=0;i<num;i++){
        p=Init();
        p->next=head->next;
        head->next=p;
        p=NULL;
    }
}

void DeleteList(NodeList* head){
    NodeList* p=head->next,*q;
    if(p){
        q=p->next;
        free(p);
        p=q;
    }
    free(head);
}

int main() {
    int num,sum=0;
    NodeList* head,*p;
    scanf("%d",&num);
    head=Init();
    CreateList(head, num);
    p=head->next;
    for(int i=0;i<num;i++){
        scanf("%d ",&(p->num));
        sum+=p->num;
        p=p->next;
    }
    printf("%d",sum);
    DeleteList(head);

}

全部评论

相关推荐

04-13 09:56
已编辑
嵌入式工程师
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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