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

牛牛的单链表求和

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

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

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

Node* createlist(int num)
{
    Node* head=(Node*)malloc(sizeof(Node));
    head->num=num;
    head->next=NULL;
    return head;
}

void add_node(Node* head,int num)
{
    Node* p=(Node*)malloc(sizeof(Node));
    p->num=num;
    p->next=NULL;
    Node* q=head;
    while(q->next)
    {
        q=q->next;
    }
    q->next=p;
}

int sum_node(Node* head)
{
    int res=0;
    Node *p=head;
    while(p)
    {
        res+=p->num;
        p=p->next;
    }
    return res;
}


int main() {
    int n;
    scanf("%d",&n);
    int t;
    scanf("%d",&t);
    Node* head=createlist(t);
    while(n--!=1)
    {
        scanf("%d",&t);
        add_node(head,t);
    }
    int res=sum_node(head);
    printf("%d\n",res);
    Node* p;
    while(head)
    {
        p=head;
        head=head->next;
        free(p);
    }
    return 0;
}

全部评论

相关推荐

05-22 09:23
门头沟学院 Java
点赞 评论 收藏
分享
吴offer选手:HR:我KPI到手了就行,合不合适关我什么事
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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