循环列队
public class Queue {
private int[] queueArray;
private int maxSize;
private int front;//队列首指针
private int end;//队列尾指针
private int length;//队列长度
//构造函数
public Queue(int maxSize){
this.maxSize = maxSize;
queueArray = new int[maxSize];
front = 0;
end = -1;
length = 0;
}
//插入
public void insert(int elem) throws Exception{
if(isFull()){
throw new Exception("队列已满!");
}
if(end==maxSize-1){
end = -1;
}//插入到数组尾部时,移动队尾指针到数组首
queueArray[++end] = elem;
length++;
}
//移除
public int remove() throws Exception{
if(isEmpty()){
throw new Exception("队列已空!");
}
int elem = queueArray[front++];
if(front==maxSize){
front = 0;
}//删除到数组尾部时,移动队尾指针到数组首删除
length--;
return elem;
}
//查看队头元素
public int peek(){
return queueArray[front];
}
//查看队列长度
public int length(){
return length;
}
//判空
public boolean isEmpty(){
return (length == 0);
}
//判满
public boolean isFull(){
return (length == maxSize);
}
}
优先级列队
用数组实现,为了方便移除,把队首放在了数组的尾部
public class PriorityQueue {
private int[] priorityQueueArray;
private int maxSize;
private int length;//队列长度
private int referencePoint;
//构造函数
public PriorityQueue(int maxSize,int referencePoint){
this.maxSize = maxSize;
this.referencePoint = referencePoint;
priorityQueueArray = new int[maxSize];
length = 0;
}
//插入
public void insert(int elem) throws Exception{
if(isFull()){
throw new Exception("已满!");
}
if(length==0){
priorityQueueArray[length++] = elem;
}else{
int i;//待插入的位置
for(i=length;i>0;i--){
int abs = Math.abs(elem-referencePoint);//待插入元素与基准点的绝对值
int priorAbs = Math.abs(priorityQueueArray[i-1]);
//依次从队首队尾进行比较,优先级高的依次往前移,新元素插入到后面
if(abs<=priorAbs){
priorityQueueArray[i] = priorityQueueArray[i-1];
}else{
break;
}
}
//插入新元素
priorityQueueArray[i] = elem;//i已经在for循环里减一了
length++;
}
}
//移除
public int remove() throws Exception{
if(isEmpty()){
throw new Exception("已空!");
}
return priorityQueueArray[--length];
}
//查看队头元素
public int peek(){
return priorityQueueArray[length-1];
}
//查看队列长度
public int length(){
return length;
}
//判空
public boolean isEmpty(){
return (length == 0);
}
//判满
public boolean isFull(){
return (length == maxSize);
}
}
测试
public class Test1 {
@Test
public void Test() throws Exception{
Queue q = new Queue(6);
q.insert(1);
q.insert(2);
q.insert(3);
q.insert(4);
q.insert(5);
q.insert(6);
int elem = q.remove();
q.insert(7);
int elem1 = q.peek();
System.out.println("elem:"+elem);
System.out.println("elem1:"+elem1);
System.out.println("==============");
}
@Test
public void Test02() throws Exception{
PriorityQueue pq = new PriorityQueue(6, 0);
pq.insert(300);
pq.insert(30);
pq.insert(467);
pq.insert(228);
int r = pq.remove();
System.out.println("r:"+r);
int r1 = pq.remove();
System.out.println("r1:"+r1);
int r2 = pq.remove();
System.out.println("r2:"+r2);
int r3 = pq.remove();
System.out.println("r3:"+r3);
System.out.println("==============");
}
}
测试结果:
elem:1
elem1:2
==============
r:467
r1:300
r2:228
r3:30
==============