优先级队列,在哪里插入?

时间:2010-01-24 08:19:56

标签: c

所以我在实现优先级队列时遇到了麻烦。对于一个优先级队列,我需要找到第一个空的位置...这就是元素的位置,我们稍后会交换..但是我无法找出算法来找到它。

这是我到目前为止所拥有的:

void pq_insert(struct tnode* p)
{
    struct tnode* curr=NULL;
    struct tnode* prev=NULL;
   printf("inserting:%c,%f\n",p->symbol,p->freq);
   if(qhead==NULL) /*qhead is null*/
   {
    qhead = p;
        /*TODO: write code to insert when queue is empty*/
   }
   /*TODO: write code to find correct position to insert*/
    curr = qhead;
    while (curr != NULL){//I think this is wrong
        if ((curr -> left) == NULL){
            curr = curr -> right;
        }
        else{
            curr = curr -> left;
        }   
    }

   if(curr==qhead)
   {
        /*TODO: write code to insert before the current start*/

   }
   else /*insert between prev and next*/
   {
        /*TODO: write code to insert in between*/
   }
}

2 个答案:

答案 0 :(得分:0)

是的,您认为错误的代码:

while (curr != NULL){//I think this is wrong
    if ((curr -> left) == NULL){
        curr = curr -> right;
    }
    else{
        curr = curr -> left;
    }   
}

错了。无论当前节点如何,您都在将curr导航到树的某个部分。

你可能想要改变你的内心,如:

if (p->freq < curr->freq)

答案 1 :(得分:0)

我不确切知道你在这个while循环中做了什么。

while (curr != NULL){//I think this is wrong
    if ((curr -> left) == NULL){
        curr = curr -> right; // Why to go right here?!, isn't this an empty node?
    }
    else{
        curr = curr -> left;
    }   
}

如果我正在寻找最近的空(NULL)左节点,我会这样做

while (curr != NULL){
    if ((curr -> left) == NULL){//The left node is NULL. Great, I found empty node.
        curr = NULL;
    }
    else{ //hmmm, left node is not empty. Lets go left for more nodes. 
        curr = curr -> left;
    }   
}

但是像这样,搜索将只剩下了。在一些插入后,树将不会平衡。

如果你提供更多细节,那就更清楚了。