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

牛牛的单链表求和

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

#include <stdio.h>
#include<malloc.h>

struct Node {
    int val;
    struct Node* next;
};

//大框架先创建
struct Node* createNode(int val) {
    struct Node* p = NULL;
    p = (struct Node*)malloc(sizeof(struct Node));
    if (p == NULL) {
        printf("创建失败!\n");
        return NULL;
    }
    p->val = val; //f赋值
    p->next = NULL;
    return p;
}


//在插入数据
void insertNode(struct Node* q, int val) {
    struct Node* p;
    p = (struct Node*)malloc(sizeof(struct Node));
    if (p == NULL) {
        printf("创建失败!\n");
        return ;
    }
    p->val = val;
    p->next = q->next;
    q->next = p;
}

 //在打印结果
void printfNode(struct Node* h) {
    struct Node* p=h;   //参照昨天的单链表
    int sum = 0;
    while (p ->next!= NULL) {   //原本这里写了p!=NULL只过了八个用例
        sum = sum + p->val;
        p = p->next;
    }
    printf("%d", sum);
}


int main() {
    int n, i;
    scanf("%d", &n);
    int* arr = (int*)malloc(sizeof(int) * n);
    struct Node* head = createNode(0); //创建链表
    struct Node* p = head;

    for (i = 0; i < n; i++)
        scanf("%d", &arr[i]);

    head->val = arr[0];
    for (i = 1; i <= n; i++) {
        insertNode(p, arr[i]);
        p = p->next;
    }
    printfNode(head);

    free(p);
    return 0;
}

《剑指offer》刷题集 文章被收录于专栏

多刷题,写题解,加油!!!!

全部评论

相关推荐

评论
1
1
分享

创作者周榜

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