The source code is as follows:
#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; The tail pointer does not hold data 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);//Set node T related information T->key = V;t->next=pq->head-> ;next;t->prev=pq->head; Maintain double-linked list 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;//Maintain doubly linked list 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);} Does not destroy the structure of B??!! (<span style= "color: #ff0000;" > FAQ </span>) append b queue to void pqjoin at end of a (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);p rintf ("%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 ();}
Run results
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Implementation and testing of a double-linked list priority Queue ADT