struct node
{
int id;
float weight;
};
int find_last(struct node Prio_Q[])
{
int i = 1;
while (Prio_Q[i].id != -1)
{
i += 1;
}
return i;
}
void initialize_Q(struct node Prio_Q[], int size)
{
int i;
for (i = 0; i < size; i ++)
{
Prio_Q[i].id = -1;
Prio_Q[i].weight = -1;
}
//printf("The queue is %f", Prio_Q[3].weight);
}
void enque_Q(struct node Prio_Q[], struct node node, int size)
{
int i = find_last(Prio_Q);
Prio_Q[i].id = node.id;
Prio_Q[i].weight = node.weight;
printf("The last index is %d\n", i);
heapify_up(Prio_Q, i);
}
void heapify_up(struct node Prio_Q[], int i)
{
if (Prio_Q[i/2].weight > Prio_Q[i].weight)
{
swap_node(Prio_Q,i/2, i);
heapify_up(Prio_Q, i/2);
}
}
void swap_node(struct node Prio_Q[], int i, int j)
{
struct node temp;
temp = Prio_Q[i];
Prio_Q[i] = Prio_Q[j];
Prio_Q[j] = temp;
//printf("smething has been swapped.\n");
}
int main(int argc, char *argv[])
{
struct node node;
struct node Prio_Q[10];
int size = 10;
initialize_Q(Prio_Q, 11);
node.id = 5;
node.weight = 11;
for(int m = 0; m < size+1; m++)
{
printf("The %dth element in Que is %d with weight %f.\n", m, Prio_Q[m].id, Prio_Q[m].weight);
}
}
這是我構建的優先級隊列,但如果您測試代碼,您會看到該隊列會自動將節點添加到其最後一個索引,然後才實際詢問函數。C中的優先級隊列
在主函數中,我只讓節點有兩個值,但我並沒有將節點排入優先級隊列數組。該數組將自動添加節點到最後一個索引,任何人都可以幫助我嗎?
在此先感謝。
我發現你在函數'initialize_Q'中傳遞值11作爲大小的參數。您應該使用值10,因爲它是隊列向量的大小。主函數末尾的最後一個循環相同。 – rbelli 2012-03-29 00:11:14