队列(先进先出)
循环队列
public class MyQueue {
private int[] queArray;
private int front;
private int rear;
private int length;
private int maxSize;
public MyQueue(int queueSize){
maxSize = queueSize;
queArray = new int[queueSize];
front = 0;
rear = -1;
length = 0;
}
public void push(int elem){
if (isFull()) {
throw new RuntimeException("队列已满");
}
if (rear == maxSize-1) {
rear = -1;
}
queArray[++rear] = elem;
length++;
}
public int pop(){
if (isEmpty()) {
throw new RuntimeException("队列为空");
}
int elem = queArray[front++];
if (front == maxSize) {
front = 0;
}
length--;
return elem;
}
public int peak(){
if (length == 0) {
throw new RuntimeException("队列为空");
}
return queArray[front];
}
public boolean isEmpty() {
return length == 0;
}
public boolean isFull(){
return length == maxSize;
}
}
实例结果
优先级队列
public class PriorityQueue {
private int[] queArray;
private int maxSize;
private int referencePoint;
private int length;
public PriorityQueue (int maxSize , int referencePoint) {
this.maxSize = maxSize;
this.referencePoint = referencePoint;
queArray = new int[maxSize];
length = 0;
}
public void push(int elem) {
if (isFull()) {
throw new RuntimeException("队列已满");
}
if (isEmpty()) {
queArray[length++] = elem;
} else {
int i;
for (i=length;i>0;i--) {
int dis = Math.abs(elem - referencePoint);
int cur = Math.abs(queArray[i-1] - referencePoint);
//根据与相对值的绝对值大小决定在队列中的位置
if (dis >= cur) {
queArray[i] = queArray[i-1];
} else {
break;
}
}
queArray[i] = elem;
length++;
}
}
public int pop(){
if (isEmpty()) {
throw new RuntimeException("队列为空");
}
int elem = queArray[--length];
return elem;
}
public int peak() {
if (isEmpty()) {
throw new RuntimeException("队列为空");
}
return queArray[length - 1];
}
public boolean isEmpty() {
return length == 0;
}
public boolean isFull() {
return length == maxSize;
}
}
实例结果