Advertisement
STANAANDREY

tp 9.10

Apr 25th, 2023
1,045
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.13 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. #include <stdlib.h>
  4.  
  5. // un element al listei
  6. typedef struct elem {
  7.   int n; // informatia utila
  8.   struct elem * next; // camp de inlantuire catre urmatorul element
  9. }
  10. elem;
  11. // aloca un nou element si ii seteaza campurile corespunzatoare
  12. elem * nou(int n, elem * next) {
  13.   elem * e = (elem * ) malloc(sizeof(elem));
  14.   if (!e) {
  15.     printf("memorie insuficienta");
  16.     exit(EXIT_FAILURE);
  17.   }
  18.   e -> n = n;
  19.   e -> next = next;
  20.   return e;
  21. }
  22. typedef struct {
  23.   elem * first; // primul element din lista
  24.   elem * last; // ultimul element din lista
  25. }
  26. List;
  27. void init(List * list) {
  28.   list -> first = NULL;
  29.   list -> last = NULL;
  30. }
  31. // adauga un element la inceputul listei
  32. void addStart(List * list, int n) {
  33.   elem * first = list -> first;
  34.   list -> first = nou(n, first);
  35.   if (!first) { // lista initiala vida - trebuie setat si ultim pe elementul adaugat
  36.     list -> last = list -> first;
  37.   }
  38. }
  39. // adauga un element la sfarsitul listei
  40. void addEnd(List * list, int n) {
  41.   elem * e = nou(n, NULL);
  42.   if (list -> last) { // adaugare in lista nevida
  43.     list -> last -> next = e;
  44.   } else { // adaugare in lista vida
  45.     list -> first = e;
  46.   }
  47.   list -> last = e;
  48. }
  49.  
  50. void printList(List * list) {
  51.   elem * crt;
  52.   for (crt = list -> first; crt; crt = crt -> next) {
  53.     printf("%d ", crt -> n);
  54.   }
  55.   putchar('\n');
  56. }
  57. // elibereaza memoria ocupata de o lista
  58. void freeList(List * list) {
  59.   elem * p, * crt = list -> first;
  60.   while (crt) {
  61.     p = crt -> next;
  62.     free(crt);
  63.     crt = p;
  64.   }
  65. }
  66.  
  67. void sepElems(List *list, List *odd, List *even) {
  68.   for (elem *it = list->first; it; it = it->next) {
  69.     if (it->n & 1) {
  70.       addEnd(odd, it->n);
  71.     } else {
  72.       addEnd(even, it->n);
  73.     }
  74.   }
  75. }
  76.  
  77. int main() {
  78.   List list, odd, even;
  79.   init(&list);
  80.   init(&odd);
  81.   init(&even);
  82.  
  83.   int n;
  84.   scanf("%d", &n);
  85.   for (int x, i = 0; i < n; i++) {
  86.     scanf("%d", &x);
  87.     addEnd(&list, x);
  88.   }
  89.  
  90.   sepElems(&list, &odd, &even);
  91.   puts("odd:");
  92.   printList(&odd);
  93.   puts("even:");
  94.   printList(&even);
  95.   freeList(&list);
  96.   freeList(&odd);
  97.   freeList(&even);//*/
  98.   return 0;
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement