利用“有序链表”来实现优先队列,链表元素按优先级递减。元素出列即出首元素,元素入列即将元素插入有序链表使其依然有序。本程序中,字符频率小则优先级高。
typedef int PQElemType;//后期需要改回HuffmanTree类型
//"优先链表"基于(有序)链表LinkList
typedef struct PQNode
{
PQElemType data;
PQNode *next;
}*LinkList;
// 定义“优先队列”类型PQueue
typedef struct
{
LinkList h; //链表的头结点
int len; //长度也“封装”其中
// bool (*Gt)(PQElemType,PQElemType);
}PQueue;
#include<iostream>
#include<stdio.h>
#include <stdlib.h>
#include"priorityQueue.h"
using namespace std;
///将数据读入pq
void ReadToPQueue(PQueue &pq)
{
PQElemType e;
pq.h = new PQNode;
pq.h->next=NULL;
pq.len=0;
while(cin>>e && e!='0')
{
PQNode *pqNew=new PQNode;
pqNew->data = e;
pqNew->next = pq.h->next;
pq.h->next = pqNew;
pq.len++;
cout << pq.h->next->data << " ";
}
return ;
}
/// 建立链式优先队列,实为排序
void BuildPQueue(PQueue &pq)
{
PQueue pqNew;
PQElemType m;
pqNew.h = new PQNode;
pqNew.h->next=NULL;
pq.h = pq.h->next;
while (pq.h)
{
Push(pqNew,pq.h->data);
pq.h = pq.h->next;
}
pq = pqNew;
return ;
}
/// 优先队列判空
bool IsEmpty(PQueue pq)
{
if(pq.h==NULL)
return true;
return false;
}
///将元素插入优先级队列(就是将元素插入有序链表,使其依然有序)
void Push(PQueue &pq, PQElemType elem)
{
PQNode *sq;
PQNode *LNew=new PQNode;
LNew->data = elem;
LNew->next = NULL;
for (sq = pq.h ; sq->next&& sq->next->data-LNew->data<0; sq = sq->next)
;
LNew->next = sq->next;
sq->next = LNew;
}
/// 从优先队列中删除并返回元素(就是删除链表第一个结点)
PQElemType Pop(PQueue &pq)
{
if(pq.h == NULL)
return -1;
PQNode *pqNew = new PQNode;
pqNew = pq.h->next;
pq.h->next = pqNew->next;
return pqNew->data;
}
这里只是优先队列的代码,哈夫曼树和编码的下一篇分享!!!