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

牛牛的单链表求和

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

全部评论

相关推荐

明天不下雨了:兄弟你是我今天看到的最好看的简历(我说的是简历风格跟简历书写)把985 211再搞亮一点。投boss就说;您好,我华科(985)研二在读,本科211。对您的岗位很感兴趣,希望能获得一次投递机会。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务