tree.c
changeset 0 af501b0c1716
child 9 c3fecc82ade6
equal deleted inserted replaced
-1:000000000000 0:af501b0c1716
       
     1 /**
       
     2  *     $Id: tree.c,v 1.1.1.1 2008-04-28 17:32:53 mbroeker Exp $
       
     3  * $Source: /development/c/demos/tree.c,v $
       
     4  *
       
     5  */
       
     6 
       
     7 #include <stdio.h>
       
     8 #include <stdlib.h>
       
     9 #include <time.h>
       
    10 
       
    11 #define GETRANDOM(max) (1+(int)((float)max*rand()/RAND_MAX+1.0))
       
    12 
       
    13 struct T {
       
    14     int data;
       
    15     struct T *next;
       
    16 };
       
    17 
       
    18 typedef struct T T;
       
    19 
       
    20 T *make_list (int elements, int rand_max)
       
    21 {
       
    22     int i;
       
    23     T *t;
       
    24     T *actual;
       
    25     T *first = NULL;
       
    26 
       
    27     srand (time (NULL));
       
    28 
       
    29     if ((t = malloc (sizeof (T) + 1)) == NULL) {
       
    30         perror ("MALLOC");
       
    31         return first;
       
    32     }
       
    33 
       
    34     t->data = GETRANDOM (rand_max);
       
    35     t->next = NULL;
       
    36 
       
    37     first = t;
       
    38 
       
    39     for (i = 1; i < elements; i++) {
       
    40         if ((actual = malloc (sizeof (T) + 1)) == NULL)
       
    41             break;
       
    42         actual->data = GETRANDOM (rand_max);
       
    43         actual->next = NULL;
       
    44         t->next = actual;
       
    45         t = actual;
       
    46     }
       
    47     return first;
       
    48 }
       
    49 
       
    50 int main (int argc, char **argv)
       
    51 {
       
    52     T *t, *actual;
       
    53 
       
    54     if (argc != 3) {
       
    55         printf ("Usage: %s elements rand_max\n", argv[0]);
       
    56         return EXIT_SUCCESS;
       
    57     }
       
    58 
       
    59     t = make_list (atoi (argv[1]), atoi (argv[2]));
       
    60 
       
    61     while (t) {
       
    62         printf ("%d\n", t->data);
       
    63         actual = t->next;
       
    64         free (t);
       
    65         t = actual;
       
    66     };
       
    67 
       
    68     return EXIT_SUCCESS;
       
    69 }