public class Main {
public static class Queue<E> {
private Object[] queue;
private int size;
private int first;
private int last;
private int realSize;
public Queue(int size) {
this.size = size;
first = 0;
last = 0;
queue = new Object[size];
}
public void push(E e) throws Exception {
if (realSize == size) {
throw new Exception("队列已满");
}
queue[++last % size] = e;
realSize++;
}
public Object pop() throws Exception {
if (realSize == 0) {
throw new Exception("队列已空");
}
realSize--;
return queue[++first % size];
}
}
public static void main(String[] args) throws Exception {
Queue<String> objectQueue = new Queue<String>(4);
objectQueue.push("1");
System.out.println(objectQueue.pop());
objectQueue.push("2");
objectQueue.push("3");
objectQueue.push("4");
System.out.println(objectQueue.pop());
objectQueue.push("5");
objectQueue.push("6");
System.out.println(objectQueue.pop());
objectQueue.push("7");
System.out.println(objectQueue.pop());
System.out.println(objectQueue.pop());
System.out.println(objectQueue.pop());
System.out.println(objectQueue.pop());
System.out.println(objectQueue.pop());
}
}
Java手写队列
最新推荐文章于 2024-05-27 13:42:30 发布