Advertisement
Guest User

Untitled

a guest
Feb 26th, 2020
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.29 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. struct Elem
  6. {
  7.     struct Elem *next;
  8.     char *str;
  9. };
  10.  
  11.  
  12. struct Elem *newElem(char *str) {
  13.     struct Elem *newN = (struct Elem*) malloc(sizeof(struct Elem));
  14.     if (newN == NULL)
  15.         return NULL;
  16.     if (str == NULL)
  17.         newN->str = NULL;
  18.     else {
  19.         newN->str = (char*)malloc(strlen(str) + 1);
  20.         strcpy(newN->str, str);
  21.     }
  22.     newN->next = NULL;
  23.     return newN;
  24. }
  25.  
  26. struct Elem *process_3(struct Elem *head, char *str, int precount) {
  27.     //первый элемент
  28.     if (head == NULL) {
  29.         head = newElem(str);
  30.         return head;
  31.     }
  32.     struct Elem *tmp = head;
  33.     int number = 1;
  34.     //вставка в начало
  35.     if (strcmp(head->str, str) > 0) {
  36.         tmp = newElem(str);
  37.         tmp->next = head;
  38.         head = tmp;
  39.         return head;
  40.     }
  41.     //поиск после какого элемента надо вставить
  42.     while(tmp->next != NULL && strcmp((tmp->next)->str, str) < 0) {
  43.         number++;
  44.         tmp = tmp->next;
  45.     }
  46.     if (tmp->next == NULL || (tmp->next != NULL && strcmp((tmp->next)->str, str) > 0)) {
  47.         //вставка в конец
  48.         if (tmp->next == NULL) {
  49.             tmp->next = newElem(str);
  50.         } else {
  51.             struct Elem *elem = newElem(str);
  52.             elem->next = tmp->next;
  53.             tmp->next = elem;
  54.         }
  55.         if (precount < 0)
  56.             precount = 0;
  57.         int first_delete = number - precount;
  58.         if (precount > number)
  59.             first_delete = 0;
  60.         tmp = head;
  61.         int i = 0;
  62.         if (first_delete == 0 && precount != 0) {
  63.             while (i != number) {
  64.                 i++;
  65.                 head = head->next;
  66.                 free(tmp->str);
  67.                 free(tmp);
  68.                 tmp = head;
  69.             }
  70.         } else {
  71.             while (i != first_delete - 1) {
  72.                 i++;
  73.                 tmp = tmp->next;
  74.             }
  75.             i = 0;
  76.             while (i != number - first_delete) {
  77.                 struct Elem *tmp2 = tmp->next;
  78.                 tmp->next = (tmp2->next);
  79.                 free(tmp2->str);
  80.                 free(tmp2);
  81.                 i++;
  82.             }
  83.         }
  84.  
  85.     }
  86.     return head;
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement