Advertisement
STANAANDREY

tp 8.3

Apr 24th, 2023
732
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.74 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdint.h>
  3. #include <string.h>
  4. #include <stdlib.h>
  5. #define NMAX 1001
  6.  
  7. void checkAlloc(const void *const p) {
  8.   if (p == NULL) {
  9.     perror("");
  10.     exit(EXIT_FAILURE);
  11.   }
  12. }
  13.  
  14. typedef struct Node {
  15.   char text[NMAX];
  16.   struct Node *prev, *next;
  17. } Node;
  18.  
  19. Node *newNode(const char s[NMAX]) {
  20.   Node *node = malloc(sizeof(Node));
  21.   checkAlloc(node);
  22.   node->next = node->prev = NULL;
  23.   strcpy(node->text, s);
  24.   return node;
  25. }
  26.  
  27. typedef struct {
  28.   Node *first, *last;
  29. } List;
  30.  
  31. void initList(List *list) {
  32.   list->first = list->last = NULL;
  33. }
  34.  
  35. void printList(const List *const list) {
  36.   for (Node *it = list->first; it; it = it->next) {
  37.     fputs(it->text, stdout);
  38.   }
  39.   fputc('\n', stdout);
  40. }
  41.  
  42. void freeList(List *list) {
  43.   Node *next;
  44.   for (Node *it = list->first; it; it = next) {
  45.     next = it->next;
  46.     free(it);
  47.   }
  48. }
  49.  
  50. void addOrd(List *list, const char text[NMAX]) {
  51.   Node *node = newNode(text);
  52.   Node *prev = NULL, *curr = list->first;
  53.   while (curr != NULL && strcmp(curr->text, text) < 0) {
  54.     prev = curr;
  55.     curr = curr->next;
  56.   }
  57.   if (prev == NULL) {//to start
  58.     node->next = list->first;
  59.     list->first = node;
  60.   } else {
  61.     prev->next = node;
  62.     node->next = curr;
  63.   }
  64. }
  65.  
  66. int main(int argc, char *argv[]) {
  67.   if (argc == 1) {
  68.     fprintf(stderr, "arg error!\n");
  69.     exit(-1);
  70.   }
  71.  
  72.   List list;
  73.   initList(&list);
  74.   FILE *file = fopen(argv[1], "r");
  75.   if (file == NULL) {
  76.     perror("");
  77.     freeList(&list);
  78.     exit(EXIT_FAILURE);
  79.   }
  80.  
  81.   static char line[NMAX];
  82.   while (fgets(line, NMAX, file)) {
  83.     addOrd(&list, line);
  84.   }
  85.  
  86.   printList(&list);
  87.   freeList(&list);
  88.   if (fclose(file) == EOF) {
  89.     perror("");
  90.   }
  91.   return EXIT_SUCCESS;
  92. }
  93.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement