- 数组实现队列
- linkedList集合实现队列
Object数组实现。
package com.bennett.test0927;
import com.sun.xml.internal.txw2.IllegalAnnotationException;
public class ArrayQueue3 {
private Object[] objects;
private int size;
private int start;
private int end;
public ArrayQueue3(int initSize) {
if (initSize < 0) {
throw new IllegalAnnotationException("the init size must more than 0.");
}
objects = new Object[initSize];
start = 0;
end = 0;
size = 0;
}
// 入队
public void push(int obj) {
if (size == objects.length) {
throw new ArrayIndexOutOfBoundsException("The queue is full.");
}
objects[end] = obj;
end = end == objects.length - 1 ? 0:end + 1;
size++;
}
// 出队
public Object pop() {
if (size == 0) {
throw new ArrayIndexOutOfBoundsException("The queue is empty.");
}
int tmp = start;
start = start == objects.length - 1 ? 0:start + 1;
size--;
return objects[tmp];
}
// 输出队首元素
public Object peek(){
if (size == 0) {
return null;
}
return objects[start];
}
// 打印队列元素
public void print() {
if (size == 0) {
throw new ArrayIndexOutOfBoundsException("The queue is empty.");
}
for (int i = start; i < objects.length; i++) {
System.out.print(objects[i]+" ");
}
}
public static void main(String[] args) {
ArrayQueue3 arrayQueue3 = new ArrayQueue3(10);
for (int i = 0; i < 10; i++) {
arrayQueue3.push(i);
}
arrayQueue3.print();
System.out.println("n队首元素:"+arrayQueue3.peek());
for (int i = 0; i < 3; i++) {
arrayQueue3.pop();
}
arrayQueue3.print();
System.out.println();
System.out.println("队首元素:"+arrayQueue3.peek());
}
}
linkedList集合实现队列
package com.bennett.test0927;
public interface MyQueue {
public boolean isEmpty();
public boolean isFull();
public void push(Object object);
public void pop();
}
package com.bennett.test0927;
import java.util.linkedList;
import java.util.List;
public class ListQueue implements MyQueue{
private List


