用java实现优先级别队列

来源:互联网 发布:windows sublime c 编辑:程序博客网 时间:2024/06/04 19:25
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[] data;

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

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

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

Element min = data[0];
for(int i = 0; i < count; i++){
if(data[i].getPriority() < min.getPriority()){
min = data[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
原创粉丝点击