package aa.datastructure;
import java.util.Arrays;
/*
* 队列
*/
public class MyQueue<E> {
private int length;//容量
private Object[] data;
private int front;//头
private int rear;
MyQueue(){
}
MyQueue(int initSize){
if(initSize>=0) {
length = initSize;
data = new Object[initSize];
front = rear = 0;
}else {
throw new RuntimeException("队列初始化大小不能小于0");
}
}
public boolean add(E e) {
if(rear == length) {
throw new RuntimeException("队列满了");
}else {
data[rear++] = e;
return true;
}
}
public E pool() {
if(front == rear) {
throw new RuntimeException("空队列");
}else {
E value = (E) data[front];
data[front++] = null;
return value;
}
}
public E peek() {
if(front == rear) {
throw new RuntimeException("空队列");
}else {
E value = (E) data[front];
return value;
}
}
public static void main(String[] args) {
MyQueue mq = new MyQueue(10);
for (int i = 0; i < 5; i++) {
mq.add(i);
}
System.out.println(Arrays.toString(mq.data));
for(int i = 0; i < 5; i++) {
System.out.println(mq.pool());
}
for(int i = 0; i < 5; i++) {
System.out.println(mq.peek());
}
}
}
使用Java实现的队列
猜你喜欢
转载自blog.csdn.net/weixin_39472101/article/details/111059887
今日推荐
周排行