【发布时间】: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