Click here to Skip to main content
15,892,072 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am implementing Priority QUE as a doubly linked list. My structs:

typedef int kintyr;

typedef struct qElem {
    struct qElem *prv;          
    kintyr *dat;                    
    int *priority;
}qElem;


typedef struct que {
    qElem *fr,*bk;              
    int cnt;                    
}que;

And this is my functions to create empty PQ, and to insert elements:

que *qNew()
{
    que *q = malloc(sizeof(*q));

if (q==NULL)
    return NULL;

q->fr = NULL;
q->bk = NULL;
q->cnt = 0;


qFault = 0;
return q;
}

que *qEnq(que *q, kintyr *x, int *prrt)
{
    que *zn=q;
    qFault = 0;
    if (q == NULL)
    {
        qFault = 1;
        return q;
    }
    if (qCHKf(q) == 1)
    {
        qFault = 3;
        return q;
    }
    qElem *new = malloc(sizeof(*new));
    new->prv = NULL;
    new->dat = x;
    new->priority=prrt;

    if (q->fr == NULL || q->fr->priority>prrt  ) 
    {
        new->prv=q->fr;
        q->fr = new;

    }
    else
    {
        que *tempas=q;
        while(tempas->fr->prv!=NULL && tempas->fr->priority<=prrt)
            tempas=tempas->fr;

        new->prv=tempas->fr;
        tempas->fr=new;
    } 
        q->cnt++;
        return q;

}

It works good if I add for example elements with priority 7, then 4, then 5.

4->5->7
But if I add element with priority 7, then 6, then 8. It appears:

6->8->7
Do you have any ideas how can I fix that?
Posted

1 solution

You have defined the priority member as a pointer to int. You probably meant to define it just as an int. For that reason the comparison in
C++
if (q->fr == NULL || q->fr->priority>prrt  )

fails. You are comparing the pointers (addresses) instead of the values. Either make priority an int, or dereference the pointer when comparing:
C++
if (q->fr == NULL || *q->fr->priority > *prrt )

The same applied to the comparison in the while statement.

Besides that your implementation has several other weaknesses:

- You never update the bk pointer of your doubly linked list
- You should use different structures for the queue object itself and the queue nodes. Otherwise, every queue node contains a surplus counter.
- If you want to have a later chance of upgrading your code to C++, don't use the new keyword for variable names.
 
Share this answer
 
Comments
Member 10664585 12-Mar-14 13:14pm    
Thank you for your answer. I made priority an int. But I found mistake further in the code. It should be: while(tempas->fr!=NULL.... and not while(tempas->fr->prv!=NULL.....

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900