源代码如下:
#include <stdlib.h> #include <stdio.h> typedef struct pq* PQ; typedef struct PQnode* PQlink; struct Item{int data;char c;}; struct PQnode{Item key;PQlink prev,next;}; struct pq{PQlink head,tail;}; PQ PQinit(){ PQ pq = (PQ)malloc(sizeof*pq); PQlink h = (PQlink)malloc(sizeof*h), t = (PQlink)malloc(sizeof*t); h->prev = t; h->next = t; t->next = h; t->prev = h; //头尾指针不存放数据 pq->head = h; pq->tail = t; return pq; } int PQempty(PQ pq){ return pq->head->next->next == pq->head; } PQlink PQinsert(PQ pq, Item v){ PQlink t = (PQlink)malloc(sizeof *t); //设置节点t的相关信息 t->key = v;t->next=pq->head->next;t->prev=pq->head; //维护双链表 t->next->prev=t;pq->head->next = t; return t; } Item PQdelmax(PQ pq){ Item max;struct PQnode *t,*x=pq->head->next; for(t=x; t->next!=pq->head;t=t->next) if(t->key.data>x->key.data) x = t; max =x->key; //维护双链表 x->next->prev=x->prev;x->prev->next=x->next; free(x);return max; } void PQchange(PQ pq, PQlink x, Item v){ x->key=v; } void PQdelete(PQ pq, PQlink x){ x->next->prev=x->prev;x->prev->next=x->next; free(x); } //并不破坏b的结构??!!(<span style="color:#ff0000;">求答疑</span>) 将b队列追加在a尾处 void PQjoin(PQ a, PQ b){ a->tail->prev->next = b->head->next; b->head->next->prev = a->tail->prev; a->head->prev = b->tail; b->tail->next = a->head; free(a->tail);free(b->head); } void test(){ PQ pq = PQinit(); PQ pq2 = PQinit(); Item a = {2,'a'}; Item b = {3,'b'}; Item c = {1,'c'}; PQinsert(pq,a);PQinsert(pq2,b);PQinsert(pq2,c); printf("%d %d \n",pq2->head->next->key.data,pq2->head->next->next->key.data); PQjoin(pq,pq2); // printf("%d %d \n",pq2->head->next->key.data,pq2->head->next->next->key.data); Item d = {21,'d'}; PQchange(pq,pq->head->next,d); PQdelete(pq,pq->head->next->next); while(!PQempty(pq)){ printf("%d \n",PQdelmax(pq).data); } } main(){ test(); }
运行结果
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/wen942467928/article/details/47733935