blob: e09d30114d9a2e74f369499f36f3c23b16a7d921 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
// A linked list on the heap: built, reversed, summed. `list_done` gets the
// finished list, the place for a tracer to look at it.
#include <stdio.h>
#include <stdlib.h>
struct node {
long value;
struct node *next;
};
__attribute__((noinline)) static struct node *push(struct node *head, long value) {
struct node *n = malloc(sizeof *n);
n->value = value;
n->next = head;
return n;
}
__attribute__((noinline)) static struct node *reverse(struct node *head) {
struct node *prev = NULL;
while (head) {
struct node *next = head->next;
head->next = prev;
prev = head;
head = next;
}
return prev;
}
__attribute__((noinline)) long list_done(struct node *head) {
long sum = 0;
for (; head; head = head->next) sum += head->value;
return sum;
}
int main(int argc, char **argv) {
int n = argc > 1 ? atoi(argv[1]) : 6;
struct node *head = NULL;
for (int i = n; i >= 1; i--) head = push(head, i * i);
head = reverse(head);
printf("sum = %ld\n", list_done(head));
return 0;
}
|