Advertisement
informaticage

Ansi C linked list

Feb 11th, 2021 (edited)
243
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JSON 2.04 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct node
  5. {
  6.     int value;
  7.     struct node* next;
  8. } node_t;
  9.  
  10. node_t* new_node(int value)
  11. {
  12.     node_t* new_node = (node_t*)malloc(sizeof(node_t*));
  13.     new_node->value = value;
  14.     new_node->next = NULL;
  15.  
  16.     return new_node;
  17. }
  18.  
  19. void print_list(node_t* head) {
  20.     while(head != NULL) {
  21.         printf("%d -> ", head->value);
  22.         head = head->next;
  23.     }
  24.  
  25.     printf("NULL");
  26. }
  27.  
  28. node_t* attach_node(node_t* head, int value) {
  29.     node_t* new_head = new_node(value);
  30.     new_head->next = head;
  31.  
  32.     return new_head;
  33. }
  34.  
  35. node_t* append_node(node_t* head, int value) {
  36.     // Head does not change
  37.     node_t* head_it = head;    
  38.  
  39.     if(head_it == NULL) {
  40.         return new_node(value);
  41.     }
  42.  
  43.     while(head_it->next != NULL) {
  44.         head_it = head_it->next;
  45.     }
  46.  
  47.     // head->null here
  48.     head_it->next = new_node(value);
  49.    
  50.     // Return the original head
  51.     return head;
  52. }
  53.  
  54. node_t* insert_at(node_t* head, size_t index, int value) {
  55.     // Head does not change
  56.     node_t* head_it = head;
  57.  
  58.     if(head_it == NULL && index != 0) {
  59.         return NULL;
  60.     }
  61.  
  62.     for(size_t i = 0; i < index && head_it->next != NULL; i++) {
  63.         head_it = head->next;
  64.     }
  65.  
  66.     // i == index or head->next == NULL
  67.     if(head_it->next == NULL) {
  68.         // End of the list reached, adding element at the end
  69.         head_it->next = new_node(value);
  70.         return head;
  71.     }
  72.  
  73.     // i == index
  74.     node_t* link = head_it->next;
  75.     head_it->next = new_node(value);
  76.     head_it->next->next = link;
  77.  
  78.     return head;
  79. }
  80.  
  81. int main(void)
  82. {
  83.     node_t* head = new_node(10);
  84.     head->next = new_node(13);
  85.     head->next->next = new_node(41);
  86.  
  87.     print_list(head);
  88.     printf("\n");
  89.  
  90.     head = append_node(head, 99);
  91.    
  92.     print_list(head);
  93.     printf("\n");
  94.  
  95.     head = attach_node(head, 12);
  96.    
  97.     print_list(head);
  98.     printf("\n");
  99.  
  100.     head = insert_at(head, 2, 66);
  101.  
  102.     print_list(head);
  103.     printf("\n");
  104.  
  105.     return 0;
  106. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement