用java实现优先级别队列

1、注意:因优先级别最高的元素被删除后,其后边的数都会往前移动,所以不会出现“假溢出”。所以不用设计成循环队列
2、包和类的结构截图:

用java实现优先级别队列 - 不惊者 - 码农小屋

3

package com.test3;

public class Element {
private Object elem;//原先意义下的数据元素
private int priority;//优先级

public Element(){

}
public Element(Object elem, int priority){
this.elem = elem;
this.priority = priority;
}
public Object getElem() {
return elem;
}
public void setElem(Object elem) {
this.elem = elem;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}

}

package com.test3;

public class SeqPQueue {
static final int defaultSize = 10;

int front;//对头
int rear;//队尾
int count;//计数器
int maxSize;//元素最大个数
Element[] da ta;

public SeqPQueue(){
this.initiate(defaultSize);
}

public SeqPQueue(int sz){
this.initiate(sz);
}
private void initiate(int sz) {
maxSize = sz;
front = rear = 0;
count = 0;
da ta = new Element[sz];
}
//从队列尾部插入对象(Element)
public void append(Object obj) throws Exception{
if(count > maxSize){
throw new Exception("full");
}
da ta[rear] = (Element)obj;
rear = rear + 1;
count++;
}

public Element delete() throws Exception{
if(count == 0){
throw new Exception("blank");
}
//priority越小优先级别越高
//将优先级别最高的数放到min中
Element min = da ta[0];
int minIndex = 0;
for(int i = 0; i < count; i++){
if(da ta[i].getPriority() < min.getPriority()){
min = da ta[i];
minIndex = i;
}
}
for(int i = minIndex+1; i < count; i++){
da ta[i-1] = da ta[i];
}
rear = rear-1;
count--;
return min;
}
//查找第一个元素
public Object getFront() throws Exception{
if(count == 0){
throw new Exception("blank");
}

Element min = da ta[0];
for(int i = 0; i < count; i++){
if(da ta[i].getPriority() < min.getPriority()){
min = da ta[i];
}
}
return min;
}
public boolean notEmpty(){
return count != 0;
}

}

package com.test3;


public class Test {
public static void main(String args[]){
SeqPQueue q = new SeqPQueue();

Element temp;

try {
//传进去的是Element对象
q.append(new Element(new Integer(1), 30));
q.append(new Element(new Integer(2), 20));
q.append(new Element(new Integer(3), 40));
q.append(new Element(new Integer(4), 20));
q.append(new Element(new Integer(5), 0));

System.out.println("进程号,优先级");
while(q.notEmpty()){
temp = q.delete();
System.out.print(temp.getElem()+" ");

System.out.println(temp.getPriority());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值