Advertisement
STANAANDREY

tp 9.6

Apr 25th, 2023
928
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.70 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 addEnd(List *list, const char text[NMAX]) {
  51.   Node *node = newNode(text);
  52.   if (!list->last) {
  53.     list->first = list->last = node;
  54.     return;
  55.   }
  56.   list->last->next = node;
  57.   node->prev = list->last;
  58.   list->last = node;
  59. }
  60.  
  61. void moveLastAtStart(List *list) {
  62.   if (!list->first || list->first == list->last) {
  63.     return;
  64.   }
  65.   Node *last = list->last;
  66.   list->last->prev->next = NULL;
  67.   last->prev = NULL;
  68.   last->next = list->first;
  69.   list->first = last;
  70. }
  71.  
  72. int main() {
  73.   List list;
  74.   initList(&list);
  75.  
  76.   int n;
  77.   scanf("%d", &n);
  78.   getchar();
  79.   static char s[NMAX];
  80.   for (int i = 0; i < n; i++) {
  81.     if (fgets(s, NMAX, stdin) == NULL) {
  82.       perror("");
  83.       exit(1);
  84.     }
  85.     addEnd(&list, s);
  86.   }
  87.   moveLastAtStart(&list);
  88.   printList(&list);
  89.   freeList(&list);
  90.   return 0;
  91. }
  92.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement