package test1;
import java.util.Arrays;
public class MyQueue {
int[] elements;
public MyQueue() {
elements = new int[0];
}
//入队
public void add(int element) {
//创建一个新的数组(长度+1)
int[] newArr = new int[elements.length + 1];
for (int i = 0; i < elements.length; i++) {
newArr[i] = elements[i];
}
//把添加的元素放入新数组中
newArr[elements.length] = element;
//使用新数组替换旧数据
elements = newArr;
}
//出队
public int poll() {
//把数组中的第0个元素取出来
int element = elements[0];
//创建一个新的数组
int[] newArr = new int[elements.length - 1];
//复制原数组中的元素到新数组中
for (int i = 0; i < newArr.length; i++) {
newArr[i] = elements[i + 1];
}
//替换新数组
elements = newArr;
return element;
}
//判断队列是否为空
public boolean isEmpty() {
return elements.length == 0;
}
//测试
public static void main(String[] args) {
//创建一个队列
MyQueue myQueue = new MyQueue();
//入队
myQueue.add(9);
myQueue.add(8);
myQueue.add(7);
//打印数组
System.out.println(Arrays.toString(myQueue.elements));//[9, 8, 7]
//出队
System.out.println(myQueue.poll());//9
System.out.println(myQueue.poll());//8
System.out.println(myQueue.isEmpty());//false
System.out.println(myQueue.poll());//7
//是否为空
System.out.println(myQueue.isEmpty());//true
//没有值,抛出数组下标越界异常
System.out.println(myQueue.poll());//Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
}
}
整体思路:
1,声明一个int数组
2,创建无参构造当实例化这个类时,会给当前对象实例一个数组
3,add()传入一个入队数据,方法内部实例了一个新的数组,长度为原数组+1长度,遍历赋值原数组进新数组,给新数组末尾赋值传入的入队数据,把新数组赋值给原数组替换
4,pull()方法创建一个新数组长度为原数组-1,循环将原数据下标+1的数据赋值给新数组,这样除了原数组第一个元素,其他元素都进入了新数组,把新数组赋值给原数组替换,返回出队的那个元素
5,isEmpty()方法返回如果原数组的长度等于0说明没有数据



