Advertisement
STANAANDREY

tp9.2

Apr 25th, 2023
874
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.97 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. int main() {
  68.   freopen("data.txt", "r", stdin);
  69.   List odd, even;
  70.   init(&odd);
  71.   init(&even);
  72.   do {
  73.     int x;
  74.     if (scanf("%d", &x) != 1) {
  75.       break;;
  76.     }
  77.     if (x & 1) {
  78.       addEnd(&odd, x);
  79.     } else {
  80.       addEnd(&even, x);
  81.     }
  82.     //break;
  83.   } while (!feof(stdin));
  84.  
  85.   puts("odd:");
  86.   printList(&odd);
  87.   puts("even:");
  88.   printList(&even);
  89.   freeList(&odd);
  90.   freeList(&even);//*/
  91.   return 0;
  92. }
  93.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement