建三个、走一遍、还三个

👁️ 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;

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

int main(void) {
    struct Node *head = make(1);
    head->next = make(2);
    head->next->next = make(3);

    int cnt = 0, sum = 0;
    for (struct Node *c = head; c != NULL; c = c->next) {
        cnt++;
        sum += c->v;
    }

    /* 一节一节还回去:**先记住下一个,再还当前这个** */
    struct Node *c = head;
    while (c != NULL) {
        struct Node *nx = c->next;
        gave++;
        free(c);
        c = nx;
    }

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

                        
👩‍🏫
AI
💬 题目评论

全部评论