fork(1) download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. struct list_t {
  5. struct list_t *next;
  6. void *value;
  7. };
  8.  
  9. struct list_t *list_new () {
  10. return (struct list_t *) malloc(sizeof(struct list_t));
  11. }
  12.  
  13. void list_free (struct list_t *xs) {
  14. struct list_t *next = NULL;
  15.  
  16. for (; xs != NULL; xs = next) {
  17. next = xs->next;
  18. free(xs);
  19. }
  20. }
  21.  
  22. struct list_t *list_reverse (struct list_t *xs) {
  23. struct list_t *ret = NULL;
  24. struct list_t *next = NULL;
  25.  
  26. for (; xs != NULL; xs = xs->next) {
  27. if ((next = list_new()) == NULL) goto err;
  28. next->value = xs->value;
  29. next->next = ret;
  30. ret = next;
  31. }
  32. goto ok;
  33.  
  34. err:
  35. list_free(ret);
  36. ok:
  37. return ret;
  38. }
  39.  
  40. struct list_t *list_int_prepend(int v, struct list_t *next) {
  41. struct list_t *this = list_new(); if (this == NULL) goto err1;
  42. void *val = malloc(sizeof(int)); if (val == NULL) goto err2;
  43. this->next = next;
  44. this->value = val;
  45. *((int*)val) = v;
  46. return this;
  47. err2:
  48. list_free(this);
  49. err1:
  50. return NULL;
  51. }
  52.  
  53. void list_int_printf(struct list_t *this) {
  54. for (; this != NULL; this = this->next) {
  55. printf("%d ", *((int*)this->value));
  56. }
  57. printf("\n");
  58. }
  59.  
  60. int main(void) {
  61. struct list_t *xs = NULL;
  62. xs = list_int_prepend(1, xs);
  63. xs = list_int_prepend(3, xs);
  64. xs = list_int_prepend(5, xs);
  65. xs = list_int_prepend(2, xs);
  66. xs = list_int_prepend(11, xs);
  67. struct list_t *ys = list_reverse(xs);
  68. list_int_printf(xs);
  69. list_int_printf(ys);
  70. list_free(xs);
  71. list_free(ys);
  72. return 0;
  73. }
Success #stdin #stdout 0s 2424KB
stdin
Standard input is empty
stdout
11 2 5 3 1 
1 3 5 2 11