优先级队列

优先级队列和通常的栈和队列一样,只不过里面的每一个元素都有一个”优先级”,在处理的时候,首先处理优先级最高的。如果两个元素具有相同的优先级,则按照他们插入到队列中的先后顺序处理。优先级队列可以通过链表,数组,堆或者其他数据结构实现。

优先级队列

树规律:左孩子节点得下标是父节点的两倍,右结点为父节点两倍加1。

分为最大堆(大根推)和最小堆(小根堆),最大堆表示最上面的为最大值。

示例代码如下:


#include 
#include 


using namespace std;

template
class PriorityQueue {
    //数组大小,不够需要扩容
    int count;
    //当前数据的角标位置
    int index = 0;
    //
    T *array = NULL;

public:
    PriorityQueue(int count);

    ~PriorityQueue();

    T pop();

    void push(T t);

    bool isEmpty();

private:
    void shiftUp(int index);

    void shiftDown(int index);
};

template
PriorityQueue::PriorityQueue(int count) {
    this->count = count;
    array = new T[count];
}


template
T PriorityQueue::pop() {
    T max = array[1];
    //把最后一个和第一个位置交换
    array[1] = array[index];
    index--;
    //往下调整堆
    shiftDown(1);
    return max;
}

template
void PriorityQueue::push(T t) {
    //判断扩容
//    count =
    
    //最后一个赋值
    array[index + 1] = t;
    index++;
    //往上调整堆
    shiftUp(index);
}

template
bool PriorityQueue::isEmpty() {
    return index == 0;
}

template
void PriorityQueue::shiftUp(int index) {
    if (index > 1 && array[index] > array[index / 2]) {
        swap(array[index], array[index / 2]);
        shiftUp(index / 2);
    }
}

template
void PriorityQueue::shiftDown(int k) {
    //是否到底
    while (k * 2 <= index) {
        //默认最大值为左孩子
        int max = k * 2;
        //有右孩子并且大于左孩子
        if (max + 1 <= index && array[max] < array[max + 1]) {
            max = max + 1;
        }
        if (array[k] > array[max]) {
            break;
        }
        //交换
        swap(array[k], array[max]);
        k = max;
    }
}


template
PriorityQueue::~PriorityQueue() {

}

你可能感兴趣的:(优先级队列)