tree.c
author Markus Bröker <mbroeker@largo.dyndns.tv>
Thu, 16 Apr 2009 12:49:12 +0200
changeset 48 b94d657a9acb
parent 47 63adb261de90
child 61 4b4c97f179da
permissions -rw-r--r--
Policy Inonsistency on many files * Whenever a piece of software terminates unexpected, * catched or not, with a help screen or not, * it indicates an ERROR and the software ==> return(s) EXIT_FAILURE committer: Markus Bröker <mbroeker@largo.homelinux.org>

/**
 * test/demos/tree.c
 * Copyright (C) 2008 Markus Broeker
 */

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define GETRANDOM(max) (1+(int)((float)max*rand()/RAND_MAX+1.0))

struct T {
    int data;
    struct T *next;
};

typedef struct T T;

T *make_list (int elements, int rand_max)
{
    int i;

    T *t, *first = NULL;

    srand (time (NULL));

    if ((t = malloc (sizeof (T))) == NULL) {
        perror ("MALLOC");
        return first;
    }

    t->data = GETRANDOM (rand_max);
    t->next = NULL;

    first = t;

    for (i = 1; i < elements; i++) {
        if ((t->next = malloc (sizeof (T))) == NULL)
            break;
        t->next->data = GETRANDOM (rand_max);
        t = t->next;
    }

    t->next = NULL;

    return first;
}

int main (int argc, char **argv)
{
    T *t, *next;

    if (argc != 3) {
        printf ("Usage: %s elements rand_max\n", argv[0]);
        return EXIT_FAILURE;
    }

    t = make_list (atoi (argv[1]), atoi (argv[2]));

    while (t) {
        printf ("%d\n", t->data);
        next = t->next;
        free (t);
        t = next;
    };

    return EXIT_SUCCESS;
}