1、顺序队列的实现代码如下所示:
public class SeqQueue {
private Object array[];
private int capacity;//队列的最大容量
private int count;//队列中元素的个数
private int front;
private int tail;
public SeqQueue(int capacity){
array = new Object[capacity];
this.capacity = capacity;
count = 0;
front = 0;
tail = 0;
}
//入队
public boolean insert(Object data){
boolean ret = (array != null) && (data != null) && (count < capacity);
if(ret){
array[tail] = data;
tail = (tail + 1) % capacity;
count++;
}
return ret;
}
//出队
public Object remove(){
Object ret = null;
if((array != null) && (count > 0)){
ret = array[front];
array[front] = null;
front = (front + 1) % capacity;
count--;
}
return ret;
}
//显示队头元素,不删除。
public Object getHead(){
return array[front];
}
//清空队列
public void clear(){
array = null;
array = new Object[capacity];
count = 0;
front = 0;
tail = 0;
}
//销毁队列
public void destroy(){
array = null;
count = 0;
front = 0;
tail = 0;
}
//判断队列是否为空
public boolean isEmpty(){
return count == 0;
}
//判断队列是否已满
public boolean isFull(){
return count == capacity;
}
//获取队列中元素的个数
public int getCount(){
return count;
}
//获取队列的容量
public int getCapacity(){
return capacity;
}
}
2、测试代码如下所示:
public class Test {
public static void main(String[] args) {
SeqQueue seqQueue = new SeqQueue(5);
seqQueue.insert("Android");
seqQueue.insert("IOS");
seqQueue.insert("Java");
seqQueue.insert("C++");
seqQueue.insert("C");
seqQueue.insert("C#");
seqQueue.insert("python");
System.out.println("队列的容量:"+seqQueue.getCapacity());
System.out.println("队列中元素的个数:"+seqQueue.getCount());
System.out.println("队头元素:"+seqQueue.getHead());
System.out.println("队列是否为空?"+seqQueue.isEmpty());
System.out.println("出队:");
while(!seqQueue.isEmpty()){
System.out.print(seqQueue.remove()+" ");
}
seqQueue.clear();
System.out.println("\n队列中元素的个数:"+seqQueue.getCount());
seqQueue.destroy();
}
}