【数据结构】优先级队列(用堆完成)


堆结构的实现源码


源码:

PriorityQueue.h

#pragma once
#ifndef __PRIORITY_QUEUE_H__
#define __PRIORITY_QUEUE_H__

#include"Heap.h"

template<class T>
class PriorityQueue
{
public:
    PriorityQueue()
    {}

    //插入
    void Push(const T& data){
        _hp.Push(data);
    }

    //删除
    void Pop(){
        _hp.Pop();
    }

    //判断是否为空
    bool Empty(){
        return _hp.Empty();
    }

    //获得优先级最高元素
    T Top(){
        return _hp.Top();
    }

    //队列元素的个数
    size_t Size(){
        return _hp.Size();
    }

private:
    Heap<T> _hp;
};

#endif  //__PRIORITY_QUEUE_H__

test.cpp

#include"Heap.h"
#include"PriorityQueue.h"
#include<iostream>
#include<stdio.h>
#include<Windows.h>
using namespace std;

//堆
void test(){
    int arr[] = { 53, 17, 78, 9, 45, 65, 87, 23 };
    Heap<int,Less<int>> hp(arr, sizeof(arr) / sizeof(arr[0]));
    hp.Push(80);
    hp.Pop();
    cout << hp.Size() << endl;
    cout << hp.Top() << endl;
    cout << hp.Back() << endl;
}

//优先级队列
void test2(){
    int arr[] = { 53, 17, 78, 9, 45, 65, 87, 23 };
    PriorityQueue<int> prq;
    for (size_t i = 0; i < sizeof(arr) / sizeof(arr[0]); ++i){
        prq.Push(arr[i]);
    }
    cout << prq.Top() << endl;
    cout << prq.Size() << endl;
    prq.Pop();
    cout << prq.Top() << endl;
    cout << prq.Size() << endl;
}

int main(){
    //test();
    test2();
    system("pause");
    return 0;
}

程序测试结果:

插入:

这里写图片描述

删除:

这里写图片描述

队头元素&队列元素个数:

这里写图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值