fork download
  1. #include <stddef.h>
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4.  
  5. typedef struct s_node s_node;
  6. typedef struct s_list s_list;
  7. struct s_node {
  8. s_node * next;
  9. };
  10. struct s_list {
  11. s_node * tail;
  12. };
  13.  
  14. s_node * append_node(s_list * list) {
  15. s_node * new_node;
  16.  
  17. new_node = malloc(sizeof *new_node);
  18. if (!new_node)
  19. return NULL;
  20.  
  21. /* Check for empty list */
  22. if (!list->tail) {
  23. new_node->next = new_node;
  24. list->tail = new_node;
  25. return new_node;
  26. }
  27.  
  28. new_node->next = list->tail->next;
  29. list->tail->next = new_node;
  30. list->tail = new_node;
  31. return new_node;
  32. }
  33.  
  34. s_node * head_node(s_list * list) {
  35. /* Check for empty list */
  36. if (!list->tail)
  37. return NULL;
  38.  
  39. return list->tail->next;
  40. }
  41.  
  42. int list_length(s_list * list) {
  43. s_node * node;
  44. int len = 0;
  45.  
  46. for (node = head_node(list); node; node = node->next) {
  47. "%p->next == %p%s\n",
  48. (void *) node,
  49. (void *) node->next,
  50. node == list->tail ? "" : " &&"
  51. );
  52. ++len;
  53. if (node == list->tail)
  54. break;
  55. continue;
  56. }
  57. return len;
  58. }
  59.  
  60. int main(void) {
  61. s_list list[1];
  62.  
  63. list->tail = NULL;
  64.  
  65. if (append_node(list) && append_node(list) && append_node(list))
  66. printf("Total nodes: %d\n", list_length(list));
  67.  
  68. return EXIT_SUCCESS;
  69. }
Success #stdin #stdout 0.01s 1852KB
stdin
Standard input is empty
stdout
0x9918008->next == 0x9918018 &&
0x9918018->next == 0x9918028 &&
0x9918028->next == 0x9918008
Total nodes: 3