优先队列实现,此处的优先队列是用于Huffman树实现的(具体参考上一篇文章)。所以用于比较的都是huffman树的node的频率,希望读者见谅。
最小堆(二叉):
template <typename T>
class MinHeap
{
public:
MinHeap(int cap );
~MinHeap();
public:
bool insert(pTree val);
bool remove(pTree data);
void print();
int size;
T getTop();
bool createMinHeap(pTree a[], int length);
private:
int capacity;
T * heap;
private:
void filterUp(int index);
void filterDown(int begin, int end);
};
template <typename T>
MinHeap<T>::MinHeap(int cap )
:capacity(cap), size(0), heap(nullptr)
{
heap = new pTree[capacity];
};
template<typename T>
MinHeap<T>::~MinHeap()
{
delete[]heap;
};
template <typename T>
void MinHeap<T>::print()
{
for (int i = 0; i < size; i++)
cout << heap[i]->freq << " ";
};
template <typename T>
T MinHeap<T>::getTop()//返回最小值
{
if (size != 0)
return heap[0];
};
template <typename T>
bool MinHeap<T>::insert(pTree val)//插入函数
{
if (size == capacity)
return false;
heap[size] = val;
filterUp(size);
size++;
return true;
};
template <typename T>
void MinHeap<T>::filterUp(int index)//由上至下进行调整
{
pTree value = heap[index];
while (index > 0)
{
int indexParent = (index-1) / 2;
if (value->freq >= heap[indexParent]->freq)
break;
else
{
heap[index] = heap[indexParent];
index = indexParent;
}
}
heap[index] = value;
};
template<typename T>
bool MinHeap<T>::createMinHeap(pTree a[], int length)
{
if (length > capacity)
return false;
for (int i = 0; i < length; i++)
{
insert(a[i]);
}
return true;
};
template<typename T>
bool MinHeap<T>::remove(pTree data)//删除元素
{
if (size == 0)
return false;
int index;
for (index = 0; index < size; index++)
{
if (heap[index]== data)
break;
}
if (index == size)
return false;
heap[index] = heap[size - 1];
size--;
filterDown(index, size);
return true;
};
template<typename T>
void MinHeap<T>::filterDown(int current, int end)//由下至上进行调整
{
int child = current * 2 + 1;
pTree value = heap[current];
while (child <= end)
{
if (child < end && heap[child]->freq > heap[child + 1]->freq)
child++;
if (value->freq<heap[child]->freq)
break;
else
{
heap[current] = heap[child];
current = child;
child = child * 2 + 1;
}
}
heap[current] = value;
};
配对堆:
class PairNode
{
public:
pTree element;
PairNode *leftChild;
PairNode *nextSibling;
PairNode *prev;
PairNode(pT