C语言 排序链表(ADT优先级队列)



我将优先级QUE实现为双链表。我的结构:

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

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

下面是创建空PQ和插入元素的函数:

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

如果我添加优先级为7,然后是4,然后是5的元素,效果会很好。

4->5->7

但是如果我添加优先级为7的元素,然后是6,然后是8。看来:

6->8->7

你有什么办法可以解决这个问题吗?

将q->fr替换为q,因此更改代码如下:

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

最新更新