fork download
  1. #include <stdio.h>
  2.  
  3. /** \brief Ein Listenelement einer einfach verketetten Liste. */
  4. struct list_element {
  5. struct list_element *next; /*!< Zeigen auf den Nachfolger in der Liste */
  6. int value; /*!< Der Wert der in einem Listenelement gespeichert wird. In diesem Beispiel ein int.*/
  7. };
  8.  
  9. /** \brief Ein Listenkopf zu verwalten einer einfach verketetten Liste. */
  10. struct list_head {
  11. struct list_element *front; /*!< Zeiger auf das erste Element der Liste. */
  12. struct list_element *end; /*!< Zeiger auf das letzte Element der Liste. */
  13. };
  14.  
  15.  
  16.  
  17. struct list_head* list_new() {
  18. return malloc(sizeof(struct list_head));
  19. }
  20.  
  21. struct list_element* list_push(struct list_head* head) {
  22.  
  23. //List head is null
  24. if(!head) {
  25. return NULL;
  26. }
  27.  
  28. //Initialize list element
  29.  
  30. struct list_element* elm = malloc(sizeof(struct list_element));
  31.  
  32. if(elm == NULL) {
  33. //Couldn't alloc memory
  34. return NULL;
  35. }
  36.  
  37. if(!(head->front)) {
  38. head->front = elm;
  39. head->end = elm;
  40. } else {
  41. //List head is not null, set next elm to point to current elm
  42. elm -> next = head -> front;
  43. head->front = elm;
  44.  
  45. }
  46.  
  47. return elm;
  48. }
  49.  
  50. int print_list(struct list_head* head) {
  51. printf("Liste: ");
  52. if(head == NULL || head->front == NULL) {
  53. printf("ist leer \n");
  54. return 0;
  55. }
  56.  
  57. struct list_element *elm = head-> front;
  58. int numberOfElements = 0;
  59.  
  60. while(elm) {
  61. printf("%i", elm -> value);
  62. printf(" ");
  63. elm = elm -> next;
  64. numberOfElements++;
  65. }
  66. printf("\n");
  67. return numberOfElements;
  68. }
  69.  
  70.  
  71.  
  72. int main(void) {
  73. struct list_head listHead = *list_new();
  74.  
  75. //First item
  76. struct list_element *element1 = list_push(&listHead);
  77. element1 -> value = 20;
  78.  
  79. //Second item
  80. struct list_element *element2 = list_push(&listHead);
  81. element2 -> value = 10;
  82.  
  83. //List is now 10 20
  84.  
  85. print_list(&listHead);
  86.  
  87. }
  88.  
Success #stdin #stdout 0s 2288KB
stdin
Standard input is empty
stdout
Liste: 10 20