I did this with six tasks. What can i get?
struct node { int data; struct node * next; }; struct node * build_123() { struct node * first = malloc(sizeof(*first)); struct node * second = malloc(sizeof(*second)); struct node * third = malloc(sizeof(*third)); assert(first && second && third); *first = (struct node){ 1, second }; *second = (struct node){ 2, third }; *third = (struct node){ 3, NULL }; return first; }
In addition, exercise is not very useful. If I wanted to create a linked list from a known set of integers, I would do something like this:
struct node { int data; struct node * next; }; #define build_list(...) \ _build_list((sizeof((int []){ __VA_ARGS__ }))/(sizeof(int)), \ (int []){ __VA_ARGS__ }) struct node * _build_list(size_t count, int values[count]) { struct node * next = NULL; for(size_t i = count; i--; ) { struct node * current = malloc(sizeof *current); assert(current); *current = (struct node){ values[i], next }; next = current; } return next; }
Then you can create an arbitrary list with
struct node * list = build_list(1, 2, 3);
Here's another version using one task, inspired by the codological answer :
struct node * build_123(void) { struct node * list = malloc(sizeof(struct node [3])); return memcpy( list, (struct node []){ { 1, list + 1 }, { 2, list + 2 }, { 3, NULL } }, sizeof(struct node [3]) ); }
Finally, I slightly changed the MSN solution - now there is no purpose:
struct node { int data; struct node * next; }; struct node * make_node(struct node * new_node, int data, struct node * next) { return memcpy(new_node, &(struct node){ data, next }, sizeof(*new_node)); } struct node * create_node(int data, struct node * next) { return make_node(malloc(sizeof(struct node)), data, next); } struct node * build_123(void) { return create_node(1, create_node(2, create_node(3, NULL))); }