一份完整的小程序跑一遍

👁️ 0 人浏览 💬 0 人评论 ❤️ 添加收藏

(本条路线统一用 gcc -std=c11 -O0 编译)建链、求和、逐个释放,最后自查:

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

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

static int got = 0, gave = 0;

static struct Node *make(int v) {
    got++;
    struct Node *n = malloc(sizeof(struct Node));
    n->v = v;
    n->next = NULL;
    return n;
}

static struct Node *build(const int *a, int n) {
    struct Node *head = NULL, *tail = NULL;
    for (int i = 0; i < n; i++) {
        struct Node *x = make(a[i]);
        if (head == NULL) { head = tail = x; }
        else { tail->next = x; tail = x; }
    }
    return head;
}

static int total(const struct Node *h) {
    int s = 0;
    for (const struct Node *c = h; c != NULL; c = c->next) s += c->v;
    return s;
}

static void release(struct Node *h) {
    while (h != NULL) {
        struct Node *nx = h->next;
        gave++;
        free(h);
        h = nx;
    }
}

int main(void) {
    int a[4] = {10, 20, 30, 40};
    int n = sizeof(a) / sizeof(a[0]);

    struct Node *head = build(a, n);
    int s = total(head);
    release(head);
    head = NULL;

    printf("%d/%d/%d/%d\n", n, s, got - gave, head == NULL);
    return 0;
}
提交你的答案
请登录后提交答案。
去登录
代码编辑器
Ctrl + Enter 运行
本次输入:
输出:

                        
👩‍🏫
AI
💬 题目评论

全部评论