blob: aaa6c8a5f40a3ef7311bd1bc0120d0a59590c90c (
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
43
44
45
46
|
// A linked list of five squares, built at its head and then reversed in
// place, argv[1] times (by default once). The last list is left standing.
// Exits with the sum of its values.
#include <stdlib.h>
struct node {
int value;
struct node *next;
};
static struct node *list;
static struct node *push(struct node *head, int value) {
struct node *n = malloc(sizeof *n);
n->value = value;
n->next = head;
return n;
}
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;
}
int main(int argc, char **argv) {
int rounds = argc > 1 ? atoi(argv[1]) : 1;
int sum = 0;
while (rounds-- > 0) {
while (list) {
struct node *next = list->next;
free(list);
list = next;
}
for (int i = 1; i <= 5; i++) list = push(list, i * i);
list = reverse(list);
sum = 0;
for (struct node *n = list; n; n = n->next) sum += n->value;
}
return sum;
}
|