建三个、走一遍、还三个
(本条路线统一用 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;
}
全部评论