fork download
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4.  
  5. //struct ListData {
  6. // int data;
  7. //};
  8.  
  9. typedef struct listItem listItem;
  10.  
  11. struct listItem {
  12. listItem* next;
  13. int value;
  14. //struct ListData* data;
  15. };
  16.  
  17. typedef struct {
  18. listItem* head;
  19. listItem* tail;
  20. } list;
  21.  
  22. listItem* listNewItemLinked(int value, listItem* next) {
  23. listItem* newItem = (listItem*)malloc(sizeof(listItem));
  24. newItem->value = value; newItem->next = next;
  25. return newItem;
  26. }
  27.  
  28. listItem* listNewItem(int value) {
  29. return listNewItemLinked(value, NULL);
  30. }
  31.  
  32. void listDelete(list* list) {
  33. listItem* current = list->head;
  34. while(current) {
  35. listItem* tmp = current->next;
  36. free(current);
  37. current = tmp;
  38. }
  39. list->head = NULL;
  40. list->tail = NULL;
  41. }
  42.  
  43. void listPush(list* list, listItem* item) {
  44. listItem* last = item;
  45. while(last->next) last=last->next;
  46. last->next = list->head;
  47. list->head = item;
  48. if (!list->tail)
  49. list->tail = last;
  50. }
  51.  
  52. void listPushBack(list* list, listItem* item) {
  53. listItem* last = item;
  54. while(last->next) last=last->next;
  55. if (list->tail)
  56. list->tail->next = item;
  57. list->tail = last;
  58.  
  59. if(!list->head)
  60. list->head = item;
  61. }
  62.  
  63. void listForEach(list* list, void (*func)(listItem* item)) {
  64. listItem* current = list->head;
  65. while(current) {
  66. func(current);
  67. current = current->next;
  68. }
  69. }
  70.  
  71. void printItem(listItem* item) {
  72. printf("%d\n", item->value);
  73. }
  74.  
  75. int main() {
  76. list l = {NULL, NULL};
  77.  
  78. //Example 1 push linked list items => 1 -> 2 -> 3 -> ...
  79. //listPush(&l, listNewItemLinked(1, listNewItemLinked(2, listNewItemLinked(3, NULL))));
  80.  
  81. //Example 2 push back => ... -> 1 -> 2 -> 3
  82. listPushBack(&l , listNewItem(1));
  83. listPushBack(&l , listNewItem(2));
  84. listPushBack(&l , listNewItem(3));
  85.  
  86. //Example 3 push front => 3 -> 2 -> 1 -> ...
  87. //listPush(&l, listNewItem(1));
  88. //listPush(&l, listNewItem(2));
  89. //listPush(&l, listNewItem(3));
  90.  
  91. //Example 4 push back linked list items => ... -> 4 -> 5 -> 6
  92. //listPushBack(&l, listNewItemLinked(4, listNewItemLinked(5, listNewItemLinked(6, NULL))));
  93.  
  94. listForEach(&l, printItem);
  95.  
  96. listDelete(&l);
  97. }
Success #stdin #stdout 0s 4568KB
stdin
Standard input is empty
stdout
1
2
3