Advertisement
Guest User

Untitled

a guest
Sep 23rd, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.48 KB | None | 0 0
  1. // Modify this file
  2. // compile with: gcc linkedlist.c -o linkedlist
  3.  
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6.  
  7. typedef struct node {
  8.         int data;
  9.         struct node* next;
  10. }node_t;
  11.  
  12. node_t* list;
  13.  
  14. void create_list() {
  15.  
  16.         system("./data.sh");
  17.         node_t* head = (node_t*)malloc(sizeof(node_t));
  18.  
  19.         FILE * fp;
  20.         char * line = NULL;
  21.         size_t len = 0;
  22.         ssize_t read;
  23.  
  24.         fp = fopen("data.txt", "r");
  25.         if (fp == NULL)
  26.             exit(EXIT_FAILURE);
  27.  
  28.         node_t* prev = head;
  29.         node_t* current = NULL;
  30.         while ((read = getline(&line, &len, fp)) != -1) {
  31.             current = (node_t*)malloc(sizeof(node_t));
  32.             current->data = atoi(line);
  33.             current->next = NULL;
  34.             prev->next = current;
  35.             prev = current;
  36.             current = NULL;
  37.         }
  38.  
  39.         fclose(fp);
  40.         if (line)
  41.             free(line);
  42.  
  43.         list = head;
  44.  
  45. }
  46.  
  47. void print_list() {
  48.         node_t* tmp = list;
  49.         while(tmp != NULL) {
  50.                 printf("%d\n", tmp->data);
  51.                 tmp = tmp->next;
  52.         }
  53. }
  54.  
  55.  
  56. void free_list() {
  57.         node_t *tmp = list->next;
  58.         node_t *freed = list;
  59.         while(tmp != NULL) {
  60.                 free(freed);
  61.                 freed = tmp;
  62.                 tmp = tmp->next;
  63.         }
  64.         free(freed);
  65. }
  66.  
  67.  
  68. int main(){
  69.  
  70.         create_list();
  71.         print_list();
  72.         free_list();
  73.  
  74.         return 0;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement