数组实现优先队列(C++)

#include <iostream>
using namespace std;
const int Size = 50;

typedef struct DataType
{
	int num;
	int priority; //优先级
} datatype;

class P_Queue
{
private:
	datatype data[Size];
	int count; //计数器

public:
	P_Queue() { count = 0; }

	int empty();
	int full();
	friend int operator<(datatype &, datatype &);
	void insertPQ(datatype); //队列的插入
	datatype deQueue();		 //队列的删除
	datatype PQueuefront();
	int PQueuesize();
	void print(datatype x)
	{
		cout << x.num << " " << x.priority << endl;
	}
};

int P_Queue::empty()
{
	return count == 0;
}

int P_Queue::full()
{
	return count == Size;
}

int operator<(datatype &b, datatype &c)
{
	return b.priority < c.priority;
}

void P_Queue::insertPQ(datatype x)
{
	if (full())
	{
		cout << "队列已满!" << endl;
		exit(1);
	}
	data[count] = x;
	count++;
}

datatype P_Queue::deQueue()
{
	if (empty())
	{
		cout << "队列空!" << endl;
		exit(1);
	}

	datatype min = data[0];
	int minindex = 0; //minidex作为最高优先级的下标
	for (int i = 0; i < count; i++)
		if (data[i] < min)
		{
			min = data[i];
			minindex = i;
		}
	data[minindex] = data[count - 1]; //把最后一个元素放在要删除元素的位置
	count--;
	return min;
}

datatype P_Queue::PQueuefront()
{
	if (empty())
	{
		cout << "队列空!" << endl;
		exit(1);
	}

	datatype min = data[0];
	for (int i = 0; i < count; i++)
		if (data[i] < min)
		{
			min = data[i];
		}
	return min;
}
int P_Queue::PQueuesize() { return count; }

void main()
{
	P_Queue *p;
	p = new P_Queue;
	datatype x;
	int t = -1;

	cout << "选项: 1.插入  2.删除 3.队列头元素 4.队列大小" << endl;
	while (1)
	{
		cout << "输入选项:";
		cin >> t;
		if (t == 1)
		{
			cout << "输入元素:";
			cin >> x.num >> x.priority;
			p->insertPQ(x);
		}
		else if (t == 2)
		{

			p->deQueue();
			cout << "删除成功!" << endl;
		}
		else if (t == 3)
		{
			p->print(p->PQueuefront());
		}
		else if (t == 4)
		{
			cout << p->PQueuesize() << endl;
		}

		else
			cout << "请重新输入:" << endl;
	}
}

 

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值