package implement;
public class MyQueue<T> {//基于数组实现
private int size ;//记录队列的大小
private T [] queue ;
private int head;//队头
private int end;//队尾
public MyQueue() {
}
public MyQueue(int initSize) {//指定队列大小
this.head = 0;
this.end = -1;
this.size = 0;
this.queue = (T[]) new Object[initSize];
}
/**
* ----------------
* | |1|2|3|4|5|6|7|
* 头 尾
*
* 实际数组容量没满,队列中还可以添加元素,尾部移动到下标为0的地方
* ----------------
* @param t
*/
public void enqueue(T t){//入队
if (isFull()) {//如果满了就抛出异常。
throw new RuntimeException();
}
if (end == queue.length-1) {//到队最后一个元素了
queue[0] =t;///添加到 index为0的位置,同时也就是对尾
end =0;
}else {
queue[++end] = t;//将数据放到对于的队尾加一中
}
size++;//容量加1
}
/**
* ---------------
* |1|2|3| | | |7|
* 尾 头
*
* ---------------
* @return
*/
public T dequeue(){//出队
T t = null;
if (isEmpty()) {//如果为空 抛出异常
throw new RuntimeException();
}
if (head == queue.length-1) {
t = queue[head];
queue[head] = null;
head = 0;
}else {
t = queue[head];
queue[head++] = null;
}
size--;
return t;
}
boolean isFull(){
return size == queue.length;
}
boolean isEmpty(){
return size == 0;
}
public static void main(String[] args) {
MyQueue<Integer> myQueue = new MyQueue<Integer>(4);
myQueue.enqueue(1);
myQueue.enqueue(2);
myQueue.enqueue(3);
myQueue.enqueue(4);
myQueue.dequeue();
System.out.println("head="+myQueue.head + ";end="+myQueue.end);
myQueue.enqueue(5);
System.out.println("head="+myQueue.head + ";end="+myQueue.end);
myQueue.dequeue();
System.out.println("head="+myQueue.head + ";end="+myQueue.end);
myQueue.enqueue(6);
System.out.println("head="+myQueue.head + ";end="+myQueue.end);
}
}
MyQueue队列的 数组实现
最新推荐文章于 2025-02-20 17:02:54 发布
