Advertisement
Guest User

linked list C

a guest
Apr 25th, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.86 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5.  
  6. typedef struct
  7. {
  8.     const char *first_name, *last_name;
  9.     float height, weight;
  10.     int age;
  11. } Human;
  12.  
  13.  
  14. struct Node;
  15. typedef struct Node Node;
  16.  
  17. struct Node
  18. {
  19.     Node* next;
  20.     Human head;
  21. };
  22.  
  23. typedef struct
  24. {
  25.     Node* root;
  26.     size_t size; // unused
  27. } LinkedList;
  28.  
  29. LinkedList create_list(void) {
  30.     LinkedList list;
  31.     list.root = NULL;
  32.     list.size = 0;
  33.     return list;
  34. }
  35.  
  36. void list_push(LinkedList* list, Human head) {
  37.     if(list->root == NULL) {
  38.         list->root = (Node*) malloc(sizeof(Node));
  39.         list->root->head = head;
  40.         list->root->next = NULL;
  41.     } else {
  42.         Node *node = list->root;
  43.        
  44.         while(node->next != NULL) {
  45.             node = node->next;
  46.         }
  47.        
  48.         node->next = (Node*) malloc(sizeof(Node));
  49.         node->next->head = head;
  50.         node->next->next = NULL;
  51.     }
  52.    
  53.     list->size++;
  54. }
  55.  
  56. Human list_access(LinkedList* list, int index) {
  57.     Node *node = list->root;
  58.     for(int i = 0; i != index; i++, node = node->next);
  59.    
  60.     return node->head;
  61. }
  62.  
  63. int main()
  64. {
  65.     LinkedList list = create_list();
  66.    
  67.     Human bob;
  68.     bob.first_name = "Bob";
  69.     bob.last_name = "Martin";
  70.     bob.height = 1.65f;
  71.     bob.weight = 140.0f;
  72.     bob.age = 74;
  73.    
  74.     Human betty;
  75.     betty.first_name = "Betty";
  76.     betty.last_name = "Martin";
  77.     betty.height = 1.55f;
  78.     betty.weight = 120.0f;
  79.     betty.age = 42;
  80.    
  81.     list_push(&list, bob);
  82.     list_push(&list, betty);
  83.     list_push(&list, bob);
  84.     list_push(&list, bob);
  85.     list_push(&list, betty);
  86.    
  87.     printf("%d\n", list.size);
  88.    
  89.     for(int i = 0; i < list.size; i++) {
  90.         Human human = list_access(&list, i);
  91.         printf("name:\t%s %s\n", human.first_name, human.last_name);
  92.     }
  93.    
  94.     return 0;
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement