如何实现锦标赛数据结构,灵活地应用于任何数据类型

时间:2017-09-28 07:05:38

标签: c data-structures

我附上了我到目前为止编写的代码。我的代码中的主要问题是解除引用void指针。我知道它不可能在c但我无助找到替代品。 问题在于2个功能setupTour和play。让我们先看看代码:

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

    typedef struct {
        int size;      /* number of players playing the Tournament*/ 
        void *largeVal; /* stores the tournament
        void *max;
        void *min;
        void *nextMax;
    } Tournament;

    /*Dynamically Allocates a space for new Tournament with each player having size "sizeofPlayer" bytes */
    Tournament *newTournament(size_t sizeofPlayer, int noOfPlayers) {
        Tournament *temp = (Tournament *) malloc(sizeof(Tournament));
        temp->size = noOfPlayers;
        temp->largeVal = (void *) malloc((2 * temp->size - 1) * sizeofPlayer);
        return temp;
    }
    /*fills the tournament leaf structure by copying the elements pointed by 'base', no of copies = tour->size. */
    Tournament *setupTour(Tournament *tour, void *base) {
        int i;
        for (i = tour->size; i < (2 * tour->size); i++) {
            *((tour->largeVal) + i - 1) = *(base++); // i am getting an error here 
                                                     // since void pointers cannot 
                                                     // be dereferenced.
        }
        return tour;
    }

    /*it is the implementation of the traditional tournament algorithm where a comparator is passed as a parameter for providing the natural ordering of the elements/players */
    Tournament *play(Tournament *tour, int (*comp)(const void *, const void *)) {
        int i;
        for (i = 2 * (tour->size) - 2;i > 1; i = i - 2) {
            void *j, *k;
            j = ((tour->largeVal) + i);
            k = ((tour->largeVal) + i - 1);
            if ((*comp)(j, k) == 1) {
                *((tour->largeVal) + ((i -1)/2)) = *j;
            }
            else {
                *((tour->largeVal) + ((i -1)/2)) = *k;
            }
        }
        return tour;
    }

    void printTour(Tournament tour, char *(*toString)(void *elem)) {
        int i;
        for (i = 0; i < 2 * tour.size - 1; i++) {
            printf("%s ", (*toString)(tour.largeVal + i));
        }
        printf("\n");
        return;
    }

`

任何人都可以帮我弄清楚如何规避这个问题。

0 个答案:

没有答案