Advertisement
informaticage

Linked lists usage example

Nov 26th, 2017
615
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.04 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. // Defining the list structure
  5. typedef struct element {
  6.     int value;
  7.     struct element *next;
  8. } element;
  9.  
  10. // Creating the list head
  11. element* init_list() {
  12.     element *head = malloc(sizeof(element));
  13.     head->value = 0;
  14.     head->next = NULL;
  15.     return head;
  16. }
  17.  
  18. // Creates a new element and pointing it's next to the old list
  19. element* append_on_top(element* list, int item_value) {
  20.     element *head = malloc(sizeof(element));
  21.     head->value = item_value;
  22.     head->next = list;
  23.     return head;
  24. }
  25.  
  26. // Iterates the list printing each and every value
  27. void print_list (const element* list) {
  28.     element *loop_list = list;
  29.     while(loop_list->next != NULL) {
  30.         printf("%d | ", loop_list->value);
  31.         loop_list = loop_list->next;
  32.     }
  33. }
  34.  
  35. int main()
  36. {
  37.     element* list = init_list();
  38.     list = append_on_top(list, 5);
  39.     list = append_on_top(list, 1);
  40.     list = append_on_top(list, 7);
  41.     list = append_on_top(list, 4);
  42.     print_list(list);
  43.     return 0;
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement