typedef int Item;
typedef struct node
{
Item data;
struct node *next,*prev;
}*PQlink;
typedef struct pq
{
PQlink header,tail;
}*PQ;
PQ createLink()
{
PQ pq = malloc(sizeof(*pq));
PQlink h = malloc(sizeof(*h));
PQlink t = malloc(sizeof(*t));
h->next = t;
h->prev = t;
t->prev = h;
t->next = h;
pq->header = h;
pq->tail = t;
return pq;
}
void insertPQ(PQ pq,Item aData)
{
PQlink t = malloc(sizeof(*t));
if (!t)
{
return;
}
t->data = aData;
PQlink x = pq->header->next;
for (;(x->next != pq->header)&&(x->data < aData);x = x->next);
if (x->next == pq->header)
{
pq->tail->prev->next = t;
t->prev = pq->tail->prev;
t->next = pq->tail;
t->next->prev = t;
}
else if(x == pq->header->next)
{
t->next = x;
t->next->prev = t;
pq->header->next = t;
t->prev = pq->header;
}
else
{
x->prev->next = t;
t->prev = x->prev;
t->next = x;
t->next->prev = t;
}
}
Item deleMax(PQ pq)
{
Item max = 0;
if (pq->header->next->next == pq->header)
{
return max;
}
PQlink x = pq->tail->prev;
for (;(x != pq->header)&&(x->prev->data == x->data); x = x->prev);//过滤相同的最大值
max = x->data;
x->prev->next = pq->tail;
pq->tail->prev = x->prev;
free(x);
return max;
}
Item deleMin(PQ pq)
{
Item min = 0;
if (pq->header->next->next == pq->header)
{
return min;
}
PQlink x = pq->header->next;
for (;(x != pq->tail)&&(x->data == x->next->data);x = x->next);
x->next->prev = pq->header;
pq->header->next = x->next;
min = x->data;
free(x);
return min;
}
void insertFunction(PQlink xa,PQ pq)
{
pq->tail->prev->next = xa;
xa->prev = pq->tail->prev;
xa->next = pq->tail;
pq->tail->prev = xa;
}
PQ joinPQ(PQ a,PQ b)
{
if (!a||!b||(a->header->next == a->tail)||(b->header->next == b->tail))
{
return NULL;
}
PQlink xa = a->header->next;
PQlink xb = b->header->next;
PQ pq = createLink();
for (;(xa != a->tail)&&(xb != b->tail);)
{
PQlink temp = NULL;
if (xa->data < xb->data)
{
temp = xa->next;
insertFunction(xa,pq);
xa = temp;
}
else if (xa->data > xb->data)
{
temp = xb->next;
insertFunction(xb,pq);
xb = temp;
}
else
{
temp = xa->next;
insertFunction(xa,pq);
xa = temp;
temp = NULL;
temp = xb->next;
insertFunction(xb,pq);
xb = temp;
}
}
if (xa != a->tail)
{
insertFunction(xa,pq);
}
if (xb != b->tail)
{
insertFunction(xb,pq);
}
free(a->header);
free(a->tail);
free(b->tail);
free(b->header);
return pq;
}