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

牛牛的单链表求和

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

全部评论

相关推荐

11-02 09:49
已编辑
货拉拉_测试(实习员工)
热爱生活的仰泳鲈鱼求你们别卷了:没事楼主,有反转查看图片
点赞 评论 收藏
分享
1 收藏 评论
分享
牛客网
牛客企业服务