tree.c
changeset 47 63adb261de90
parent 29 7abf6146898e
child 48 b94d657a9acb
equal deleted inserted replaced
46:4b9e1ac40246 47:63adb261de90
    18 
    18 
    19 T *make_list (int elements, int rand_max)
    19 T *make_list (int elements, int rand_max)
    20 {
    20 {
    21     int i;
    21     int i;
    22 
    22 
    23     T *t;
    23     T *t, *first = NULL;
    24     T *actual;
       
    25     T *first = NULL;
       
    26 
    24 
    27     srand (time (NULL));
    25     srand (time (NULL));
    28 
    26 
    29     if ((t = malloc (sizeof (T) + 1)) == NULL) {
    27     if ((t = malloc (sizeof (T))) == NULL) {
    30         perror ("MALLOC");
    28         perror ("MALLOC");
    31         return first;
    29         return first;
    32     }
    30     }
    33 
    31 
    34     t->data = GETRANDOM (rand_max);
    32     t->data = GETRANDOM (rand_max);
    35     t->next = NULL;
    33     t->next = NULL;
    36 
    34 
    37     first = t;
    35     first = t;
    38 
    36 
    39     for (i = 1; i < elements; i++) {
    37     for (i = 1; i < elements; i++) {
    40         if ((actual = malloc (sizeof (T) + 1)) == NULL)
    38         if ((t->next = malloc (sizeof (T))) == NULL)
    41             break;
    39             break;
    42         actual->data = GETRANDOM (rand_max);
    40         t->next->data = GETRANDOM (rand_max);
    43         actual->next = NULL;
    41         t->next->next = NULL;
    44         t->next = actual;
    42         t = t->next;
    45         t = actual;
       
    46     }
    43     }
    47     return first;
    44     return first;
    48 }
    45 }
    49 
    46 
    50 int main (int argc, char **argv)
    47 int main (int argc, char **argv)
    51 {
    48 {
    52     T *t, *actual;
    49     T *t, *next;
    53 
    50 
    54     if (argc != 3) {
    51     if (argc != 3) {
    55         printf ("Usage: %s elements rand_max\n", argv[0]);
    52         printf ("Usage: %s elements rand_max\n", argv[0]);
    56         return EXIT_SUCCESS;
    53         return EXIT_SUCCESS;
    57     }
    54     }
    58 
    55 
    59     t = make_list (atoi (argv[1]), atoi (argv[2]));
    56     t = make_list (atoi (argv[1]), atoi (argv[2]));
    60 
    57 
    61     while (t) {
    58     while (t) {
    62         printf ("%d\n", t->data);
    59         printf ("%d\n", t->data);
    63         actual = t->next;
    60         next = t->next;
    64         free (t);
    61         free (t);
    65         t = actual;
    62         t = next;
    66     };
    63     };
    67 
    64 
    68     return EXIT_SUCCESS;
    65     return EXIT_SUCCESS;
    69 }
    66 }