void buildHuffmanTree() { //if pq is empty then nothing to do if(empty()){ return; } //while queue has more than 1 node //NOTE: I wrote a size() function for the pq to make this easy while(size() > 1) { //grab 2 smallest nodes p1 and p2 from pq node *p1 = pqmindelete(); node *p2 = pqmindelete(); //create new node that is sum of p1 and p2 frequencies //create new parent node *p = getNode(p1->info + p2->info); //set p to be parent of p1 and p2 p1->parent =p; p2 -> parent =p; //setleft p1 p1->left = p1; //setright p2 p2->right = p2; //put p in pq pqinsert(p); //last node in pq is the root so get it from pq and assign to root } root = pqmindelete(); }
main() { int ch,e,temp,old; pq.front=pq.rear=SIZE-1; while(1) { system("cls"); char ch1='N'; printf("\n\n\nPriority Queue Implementation\n\n\n"); printf("1. Insert Elements\n"); printf("2. Delete Smallest Element\n"); printf("3. Delete Largest Element\n"); printf("4. Display Elements\n"); printf("5. Quit\n\n"); printf("Enter Choice:"); scanf("%d",&ch); switch(ch) { case 1: printf("\nEnter Element:"); scanf("%d",&temp); pqinsert(&pq,temp); break; case 2: fflush(stdin); if(emptys(&pq)) { printf("\nUnderflow"); getchar(); break; } if(pq.front==SIZE-1) printf("\nDelete %d (Y/N)?", pq.elements[0]); else printf("\nDelete %d (Y/N)?", pq.elements[pq.front+1]); scanf("%c", &ch); if(ch=='Y' || ch=='y') { temp=pqmindelete(&pq); printf("\n%d Deleted !",temp); fflush(stdin); getchar(); } break; case 3: fflush(stdin); if(emptys(&pq)) { printf("\nUnderflow"); getchar(); break; } printf("\nDelete %d (Y/N)?", pq.elements[pq.rear]); scanf("%c", &ch); if(ch=='Y' || ch=='y') { temp=pqmaxdelete(&pq); printf("\n%d Deleted !",temp); fflush(stdin); getchar(); } break; case 4: fflush(stdin); if(pq.front==pq.rear) { printf("\nPriority Queue Empty"); getchar(); break; } old=pq.front; printf("\nPriority Queue List: "); while(pq.front!=pq.rear) { if(pq.front==SIZE-1) pq.front=0; else pq.front++; printf("%d->",pq.elements[pq.front]); } getchar(); pq.front=old; break; case 5: exit(1); default: printf("\nIncorrect Choice"); fflush(stdin); getchar(); } } }