簡體   English   中英

C中的優先級隊列

[英]Priority Queue in C

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);
    }

}

這是我構建的優先級隊列,但是如果您測試代碼,您將看到該隊列會在我實際要求該函數這樣做之前將節點自動添加到其最后一個索引。

在main函數中,我僅使節點具有兩個值,但沒有將節點排隊到優先級隊列數組中。 數組會自動將節點添加到最后一個索引,有人可以幫我嗎?

提前致謝。

歡迎來到C; 該語言無法幫助您避免越界訪問數組,這是代碼中的一個特殊問題:

main()

struct node Prio_Q[10];

int size = 10;
initialize_Q(Prio_Q, 11);

請注意,您正在調用size11 initialize_Q() 這意味着您的for循環將導致對數組的訪問超出了Prio_Q數組的末尾

void initialize_Q(struct node Prio_Q[], int size)
{

    int i;

    for (i = 0; i < size; i ++)
    {
        Prio_Q[i].id = -1;      /* BUG when i == 10 */
        Prio_Q[i].weight = -1;

您可能應該使用# #defineenumconst變量將數組的大小存儲在一個位置 這將大大減少編寫此類小錯誤的機會。

find_last()函數應該做一些邊界上數組的大小檢查。 如果您的其余代碼沒有錯誤,此代碼應該可以正常工作。 您也可以重新編寫此函數,以確保它沒有脫離數組的末尾。 (它將如何處理一個完整的數組?提示:很差。

int find_last(struct node Prio_Q[])
{
    int i = 1;
    while (Prio_Q[i].id != -1)
    {
        i += 1;
    }return i;
}

對於您的輸出(應該是它自己的功能,因此您可以在整個程序中隨意使用它):

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);
}

同樣,當m == 10時,您已經訪問了數組末尾。

您正在語句struct node Prio_Q[10];中初始化大小為10 [索引0,1,..,9]的數組struct node Prio_Q[10];

但是,當您初始化隊列initialize_Q(Prio_Q, 11); 您將其初始化為大小11:[0,1,...,10]。 您正在從分配的數組中溢出!

以后在for(int m = 0; m < size+1; m++)打印元素時for(int m = 0; m < size+1; m++)發生同樣的情況for(int m = 0; m < size+1; m++)

請記住,在c數組中索引從0開始,因此,如果您有n元素,則索引為[0,1,...,n-1] -因此,您的迭代應從i = 0i < n

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM