tree.c
author Markus Bröker <mbroeker@largo.dyndns.tv>
Thu, 16 Apr 2009 12:49:12 +0200
changeset 43 cf8c1b5127b2
parent 29 7abf6146898e
child 47 63adb261de90
permissions -rw-r--r--
vector.cc Testcase -> Eine Referenz ist günstiger bei Vektoren -> move ist ohne Referenz flexibler -> Es werden weniger Objekte erzeugt und dementsprechend auch wieder zerstört. 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;
    T *actual;
    T *first = NULL;

    srand (time (NULL));

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

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

    first = t;

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

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

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

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

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

    return EXIT_SUCCESS;
}