fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stddef.h>
  4.  
  5. typedef struct links {
  6. struct links * next;
  7. struct links * prev;
  8. } links;
  9.  
  10. typedef struct outer_node {
  11. links l; // links to outer_node.l
  12. struct inner_node * children;
  13. } outer_node;
  14.  
  15. typedef struct inner_node {
  16. links l; // links to inner_node.l
  17. char type;
  18. void * item;
  19. } inner_node;
  20.  
  21. void linkNodes(links* l1, links* l2)
  22. {
  23. links* tmp = l1->prev;
  24. l1->next->prev = l2->prev;
  25. l1->next = l2;
  26.  
  27. l2->prev->next = tmp;
  28. l2->prev = l1;
  29. }
  30.  
  31. inner_node* createNode(char type, void* item, inner_node* sibling)
  32. {
  33. inner_node* n = malloc(sizeof(*n));
  34. n->type = type;
  35. n->item = item;
  36. n->l.prev = &n->l;
  37. n->l.next = &n->l;
  38. if (sibling != NULL)
  39. linkNodes(&n->l, &sibling->l);
  40. return n;
  41. }
  42.  
  43. outer_node* createOuterNode(inner_node* child, outer_node* sibling)
  44. {
  45. outer_node* n = malloc(sizeof(*n));
  46. n->l.prev = &n->l;
  47. n->l.next = &n->l;
  48. n->children = child;
  49. if (sibling != NULL)
  50. linkNodes(&n->l, &sibling->l);
  51. return n;
  52. }
  53.  
  54. void PrintList(links* l, int level)
  55. {
  56. links* l2 = l;
  57. do
  58. {
  59. if (level == 0)
  60. {
  61. outer_node* n = (void*)((char*)l2 + offsetof(outer_node, l));
  62. printf("{\n");
  63. PrintList(&n->children->l, level + 1);
  64. printf("}\n");
  65. }
  66. else
  67. {
  68. inner_node* n = (void*)((char*)l2 + offsetof(inner_node, l));
  69. printf(" type: %d, item: %s\n", n->type, (char*)n->item);
  70. }
  71. l2 = l2->next;
  72. } while (l2 != l);
  73. }
  74.  
  75. int main(void)
  76. {
  77. outer_node* root =
  78. createOuterNode(
  79. createNode(0, "something",
  80. NULL
  81. ),
  82. createOuterNode(
  83. createNode(1, "foo",
  84. createNode(2, "bar",
  85. NULL
  86. )
  87. ),
  88. createOuterNode(
  89. createNode(3, "red",
  90. createNode(3, "green",
  91. createNode(3, "blue",
  92. NULL
  93. )
  94. )
  95. ),
  96. createOuterNode(
  97. createNode(4, "cat",
  98. createNode(5, "dog",
  99. createNode(6, "raven",
  100. createNode(7, "shark",
  101. NULL
  102. )
  103. )
  104. )
  105. ),
  106. NULL
  107. )
  108. )
  109. )
  110. );
  111.  
  112. PrintList(&root->l, 0);
  113.  
  114. return 0;
  115. }
  116.  
Success #stdin #stdout 0s 1920KB
stdin
Standard input is empty
stdout
{
  type: 0, item: something
}
{
  type: 1, item: foo
  type: 2, item: bar
}
{
  type: 3, item: red
  type: 3, item: green
  type: 3, item: blue
}
{
  type: 4, item: cat
  type: 5, item: dog
  type: 6, item: raven
  type: 7, item: shark
}