在c中颠倒弹出优先级队列的顺序

时间:2016-08-07 05:56:54

标签: c heap priority-queue

我有这个代码从队列中弹出优先级最高的节点。目前最高优先级定义为1.我想更改此优先级,因此最高优先级为10 - > 1.为了澄清问题在于pop函数,其他的只是为了上下文添加。

节点和堆定义:

struct intnode {
    int value;
    int priority;
};
typedef struct intnode IntNode;

struct heap {
    IntNode *nodes;
    int len;
    int size;
};
typedef struct heap heap_t;

这是队列的推送功能:

void push (heap_t *h, int priority, int value) {
    if (h->len + 1 >= h->size) {
        if(h->size) {
            h->size = h->size * 2;
        } 
        else {
            h->size = 4;
        }

        h->nodes = (IntNode *)realloc(h->nodes, h->size * sizeof (IntNode));
    }

    int i = h->len + 1;
    int j = i / 2;

    while (i > 1 && h->nodes[j].priority > priority) {
        h->nodes[i] = h->nodes[j];
        i = j;
        j = j / 2;
    }

    h->nodes[i].value = value;
    h->nodes[i].priority = priority;
    h->len++;
}

队列的pop函数:

int pop (heap_t *h) {
    int i, j, k;

    if (!h->len) {
        return -1;
    }

    int value = h->nodes[1].value;

    h->nodes[1] = h->nodes[h->len];
    h->len--;
    i = 1;

    while (1) {
        k = i;
        j = 2 * i;

        if (j <= h->len && h->nodes[j].priority < h->nodes[k].priority) {
            k = j;
        }
        if (j + 1 <= h->len && h->nodes[j + 1].priority < h->nodes[k].priority) {
            k = j + 1;
        }
        if (k == i) {
            break;
        }

        h->nodes[i] = h->nodes[k];
        i = k;
    }

    h->nodes[i] = h->nodes[h->len + 1];

    return value;
}

感谢您的时间!

1 个答案:

答案 0 :(得分:0)

只需使用11 - your priority

推送您的元素