×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: C
Posted by: Rob Green
Added: Sep 20, 2022 5:12 PM
Modified: Sep 20, 2022 5:17 PM
Views: 1
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. //https://code-vault.net/lesson/nk297jhs1m:1641837289454
  5.  
  6. typedef struct Node {
  7.     int x;
  8.     struct Node* next;
  9. } Node;
  10.  
  11. void deallocate(Node** root) {
  12.     Node* curr = *root;
  13.     while (curr != NULL) {
  14.         Node* aux = curr;
  15.         curr = curr->next;
  16.         free(aux);
  17.     }
  18.     *root = NULL;
  19. }
  20.  
  21. void insert_end(Node** root, int value) {
  22.     Node* new_node = malloc(sizeof(Node));
  23.     if (new_node == NULL) {
  24.         exit(1);
  25.     }
  26.     new_node->next = NULL;
  27.     new_node->x = value;
  28.  
  29.     if (*root == NULL) {
  30.         *root = new_node;
  31.         return;
  32.     }
  33.  
  34.     Node* curr = *root;
  35.     while (curr->next != NULL) {
  36.         curr = curr->next;
  37.     }
  38.     curr->next = new_node;
  39. }
  40.  
  41. void serialize(Node* root) {
  42.     FILE* file = fopen("list.txt", "w");
  43.     if (file == NULL) {
  44.         exit(1);
  45.     }
  46.  
  47.     for (Node* curr = root; curr != NULL; curr = curr->next) {
  48.         fprintf(file, "%d, ", curr->x);
  49.     }
  50.     fclose(file);
  51. }
  52.  
  53. void deserialize(Node** root) {
  54.     FILE* file = fopen("list.txt", "r");
  55.     if (file == NULL) {
  56.         exit(2);
  57.     }
  58.  
  59.     int val;
  60.     while(fscanf(file, "%d, ", &val) > 0) {
  61.         insert_end(root, val);
  62.     }
  63.     fclose(file);
  64. }
  65.  
  66. int main(int argc, char* argv[]) {
  67.     Node* root = NULL;
  68.     Node* root2 = NULL;
  69.  
  70.      insert_end(&root, -2);
  71.      insert_end(&root, 11);
  72.      insert_end(&root, 22);
  73.      serialize(root);
  74.     deserialize(&root);
  75.  
  76.     for (Node* curr = root; curr != NULL; curr = curr->next) {
  77.         printf("%d\n", curr->x);
  78.     }
  79.  
  80.     deallocate(&root);
  81.     // deallocate(&root2);
  82.  
  83.     return 0;
  84. }
  85.  
  86. list.txt
  87. 2, 11, 22,