fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. struct list {
  5. int value;
  6. struct list *next;
  7. };
  8.  
  9. void list_add(struct list **li, int value);
  10. struct list *list_fromarray(int *v, int n);
  11. void list_print(struct list *li, const char *msg);
  12. void list_free(struct list *li);
  13.  
  14. int main(void) {
  15. struct list *list;
  16. int test[] = {1, 4, 8, 9, 13, 42};
  17. list = list_fromarray(test, sizeof test/sizeof *test);
  18. list_print(list, "final list");
  19. list_free(list);
  20. }
  21.  
  22. struct list *list_fromarray(int *v, int n) {
  23. struct list *li = NULL;
  24. for (int k = n - 1; k >= 0; k--) {
  25. list_add(&li, v[k]);
  26. }
  27. return li;
  28. }
  29.  
  30. void list_add(struct list **li, int value) {
  31. struct list *node;
  32. node = malloc(sizeof *node);
  33. node->value = value;
  34. node->next = *li;
  35. *li = node;
  36. }
  37.  
  38. void list_print(struct list *li, const char *msg) {
  39. printf("%s:", msg);
  40. while (li) {
  41. printf(" %d", li->value);
  42. li = li->next;
  43. }
  44. puts("");
  45. }
  46.  
  47. void list_free(struct list *li) {
  48. while (li) {
  49. struct list *bak = li;
  50. li = li->next;
  51. free(bak);
  52. }
  53. }
  54.  
Success #stdin #stdout 0s 2140KB
stdin
Standard input is empty
stdout
final list: 1 4 8 9 13 42