堆是由数组实现的队列,由完全二叉树层序放置。
```c
package com.liuheizi.demo;
import java.util.Arrays;
class NullArrayEcxeption extends RuntimeException {//自定义异常
public NullArrayEcxeption() {
super();
}
public NullArrayEcxeption(String message) {
super(message);
}
}
class MyQueue {//创建堆
private int[] array;
private int usedSize;
public MyQueue() {
this.array = new int[10];
}
public MyQueue(int[] array) {
this.usedSize = array.length;
this.array = array;
}
public int[] getArray() {
return array;
}
public int peek() {//获取元素值
if (this.isEmpty()) {
throw new NullArrayEcxeption("获取失败");
}
return this.array[0];
}
public void poll() {//弹出元素值
if (this.isEmpty()) {
throw new NullArrayEcxeption("出队失败");
}
int temp = this.array[0];
this.array[0] = this.array[this.usedSize - 1];
this.array[this.usedSize - 1]=temp;
adjustDowm(0);
this.usedSize--;
}
public void offer(int i) {//入队列
if (usedSize + 1 > this.array.length) {
int newSize = this.array.length << 1 + 2;
if (newSize < usedSize + 1) {
newSize = usedSize + 1;
}
this.array = Arrays.copyOf(this.array, newSize);
}
this.array[this.usedSize++] = i;
this.adjustUp(usedSize-1);
}
public boolean isEmpty() {
return usedSize == 0;
}
public boolean isFull() {
return usedSize == this.array.length;
}
public void adjustDowm(int parent) {//向下调整
int child = parent * 2 + 1;
while (child <= this.usedSize - 1) {
if (child + 1 <= this.usedSize - 1 && array[child] < array[child + 1]) {
child++;
}
if (this.array[parent] < this.array[child]) {
int temp = array[parent];
array[parent] = array[child];
array[child] = temp;
}
parent = child;
child = child * 2 + 1;
}
}
public void adjustTree() {//调整棵树为堆结构
for (int i = (this.usedSize - 2) / 2; i >= 0; i--) {
this.adjustDowm(i);
}
}
public void adjustUp(int child) {//向上调整
int parent = (child - 1) / 2;
while (child > 0) {
if (this.array[child] > this.array[parent]) {
int temp = array[child];
array[child] = array[parent];
array[parent] = temp;
child = parent;
parent = (parent - 1) / 2;
} else {
break;
}
}
}
public void printMyArray() {
for (int i = 0; i <this.usedSize ; i++) {
System.out.print(this.array[i]+" ");
}
}
}
public class TestDemo3 {
public static void main(String[] args) {
int[] array = {};
MyQueue myQueue = new MyQueue(array);
myQueue.poll();
myQueue.printMyArray();
}
}