package Queue;
//用数组实现自己的队列
public class Queue {
private static int DEFAULT_SIZE=100;
private Object[] queue;
private int front;
private int tail;
private int thelength;
public Queue(){
thelength=DEFAULT_SIZE;
init();
}
public Queue(int length){
thelength=length;
init();
}
public int size(){
return (front-tail+queue.length)%queue.length;
}
private void init() {
queue=new Object[thelength+1];
tail=front=0;
}
//入队列
public void put(Object e) throws Exception{
if(isFull()){
throw new Exception("队列已经满了,添加失败!");
}
queue[front]=e;
front=(front+1)%queue.length;
}
//出队列
public Object get() throws Exception{
if(isEmpty()){
throw new Exception("队列为空,删除失败!");
}
Object e=queue[tail];
queue[tail]=null;
tail=(tail+1)%queue.length;
return e;
}
//清空队列
public void clear(){
queue=null;
queue=new Object[thelength];
}
public boolean isEmpty() {
return front==tail;
}
//判断队列是否已满
public boolean isFull() {
return (front+1)%queue.length==tail;
}
public static void main(String[] args){
Queue que=new Queue(4);
char[] data=new char[]{'沧', '海','一','声'};
try {
for(int i=0;i
java 实现数组队列和链表队列
最新推荐文章于 2019-12-14 17:08:29 发布