【问题标题】:Sorting linked list (ADT Priority Que)排序链表(ADT Priority Que)
【发布时间】:2014-03-12 14:22:33
【问题描述】:

我将优先级 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

您有什么想法可以解决这个问题吗?

【问题讨论】:

    标签: c pointers linked-list priority-queue abstract-data-type


    【解决方案1】:

    将 q->fr 替换为 q。所以修改代码如下。

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

    【讨论】:

      猜你喜欢
      • 2014-04-15
      • 2018-05-10
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      • 2018-07-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多