数据结构之优先级队列的java实现

package com.cb.java.algorithms.datastructure.yanweimindatastructure.list;


public class GenericPriorityQ<T extends Comparable<T>> {
private int maxSize; // 优先级队列容量
private int length; // 优先级队列中元素个数
private T[] priorityQ; // 优先级队列


public GenericPriorityQ(int size) {
maxSize = size;
priorityQ = (T[]) new Comparable[maxSize];
length = 0;
}


/**
* 将元素x插入优先级队列中

* @param x
*/
public void insert(T x) {
int j = 0;
if (length == 0) {
priorityQ[length] = x;
length++;
} else {
for (j = length - 1; j >= 0; j--) {
// 如果要插入的元素比队列中元素大。则把队列中元素往队列头部方向移动
if (x.compareTo(priorityQ[j]) > 0)
priorityQ[j + 1] = priorityQ[j];
else{

break;
}
}
priorityQ[j+1]=x;
length++;
}
}

/**
* 最小元素出队
* @return
*/
public T remove()
{
return priorityQ[--length];
}

/**
* 获取队列中最小元素
* @return
*/
public T peek()
{
return priorityQ[length-1];
}

/**
* 判断队列是否为空
* @return
*/
public boolean isEmpty()
{
return length==0;
}
/**
* 判断队列是否已满
* @return
*/
public boolean isFull()
{
return length==maxSize;
}

/**
* 获取队列长度
* @return
*/
public int size()
{
return length;
}
}

猜你喜欢

转载自blog.csdn.net/u013230189/article/details/80654047