您的位置:首页 > 编程语言 > Java开发

Java用数组实现顺序队列

2011-05-17 19:38 579 查看
import java.util.*;

/**

* 顺序存储结构队列

*/

public class Queue {

private static final int MAX_SIZE = 100;

private Object[] queue; //队列

private int front; //头指针

private int rear; //尾指针

private int length; //队列初始化长度

//初始化队列

private void init(){

queue = new Object[this.length + 1];

front = rear = 0;

}

//入队

public void put(Object object) throws Exception{

if(isFull()){

throw new Exception("入队失败!队列已满!");

}

queue[rear] = object;

rear = (rear + 1) % queue.length;

}

//出队

public Object get() throws Exception{

if(isEmpey()){

throw new Exception("出队失败!队列为空!");

}

Object object = queue[front];

queue[front] = null; //释放对象

front = (front + 1) % queue.length;

return object;

}

//清空队列

public void clear(){

queue = null;

queue = new Object[this.length];

}

//获得队列当前大小

public int size(){

return (rear - front + queue.length ) % queue.length;

}

//判断队列是否已满

public boolean isFull(){

return (rear + 1) % queue.length == front;

}

//判断队列是否为空

public boolean isEmpey(){

return front == rear;

}

public Queue(){

this.length = MAX_SIZE;

init();

}

public Queue(int length){

this.length = length;

init();

}

public static void main(String[] args) {

Queue queue = new Queue(5);

char[] data = new char[]{'沧','海','一','声','笑'};

try {

for (int i = 0; i < data.length; i++) {

System.out.println("入队数据:" + data[i]);

queue.put(data[i]);

}

System.out.println("队大小:" + queue.size());

System.out.println("---------------------");

while(!queue.isEmpey()){

System.out.println("出队数据:" + queue.get());

}

System.out.println("队空否?/t" + queue.isEmpey());

} catch (Exception e) {

e.printStackTrace();

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: