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

牛牛的单链表求和

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

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

typedef struct Node {
    int data;
    struct Node* next;
}Node;

// 链表初始化
Node* initList() {
    Node* list = (Node*)malloc(sizeof(Node));
    list->next = NULL;
    list->data = 0;
    return list;
}

// 尾插法
void tailInsert(Node* list, int data) {
    Node* node = (Node*)malloc(sizeof(Node));
    node->data = data;
    node->next = NULL;

    Node* head = list; // 指针移动到第一个节点的位置
    while (head->next != NULL) {
        head = head->next;
    }

    head->next = node;
    list->data ++ ;
}

// 链表元素求和
int getSum(Node* list) {
    int sum = 0;
    Node* head = list->next;
    while (head) {
        sum += head->data;
        head = head->next;
    }
    return sum;
}
int main()
{

    int n;
    scanf("%d", &n);

    Node* list = initList();

    for (int i = 0; i < n; i ++ )
    {
        int x;
        scanf("%d", &x);

        tailInsert(list, x);
    }

    printf("%d", getSum(list));

    return 0;
}

全部评论

相关推荐

09-01 11:31
门头沟学院 Java
buul:七牛云的吧,感觉想法是好的,但是大家没那么多时间弄他这个啊。。。不知道的还以为他是顶尖大厂呢还搞比赛抢hc,只能说应试者的痛苦考察方是无法理解的,他们只会想一出是一出
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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