- package com.tw.dst.sq;
- /**
- * <p>队列是一种先进先出(FIFO)的线性数据结构,常用操作有插入(insert)和删除(remove)</p>
- * @author tangw 2010-11-27
- */
- public class Queue {
- // 队列数组
- private long queueArr[];
- //队列的前端下标
- private int front;
- //队列的尾端下标
- private int rear;
- //队列的大小
- private int maxSize;
- //队列中元素的个数
- private int nItems;
- //初始化一个大小为size的队列
- public Queue(int size){
- queueArr = new long[size];
- maxSize = size;
- front = 0;
- rear = -1;
- nItems = 0;
- }
- //插入操作
- public void insert(long value){
- //队列已满
- if(rear == maxSize-1)
- rear = -1;
- queueArr[++rear] = value;
- nItems++;
- }
- //删除操作
- public long remove(){
- long temp = queueArr[front++];
- if(front == maxSize)
- front = 0;
- nItems--;
- return temp;
- }
- //返回队列第一个元素
- public long peakFront(){
- return queueArr[front];
- }
- //判断是否为空
- public boolean isEmpty(){
- return nItems == 0;
- }
- //判断是否已满
- public boolean isFull(){
- return nItems == maxSize;
- }
- //返回队列中元素的个数
- public int size(){
- return nItems;
- }
- public void print(){
- for(int i = front;i < front+nItems;i++){
- System.out.print(queueArr[i]+" ");
- }
- System.out.println();
- }
- public static void main(String[] args) {
- Queue q = new Queue(10);
- while(!q.isFull()){
- long value = (long)(Math.random()*100);
- q.insert(value);
- }
- q.print();
- while(!q.isEmpty()){
- q.remove();
- q.print();
- }
- q.print();
- System.out.println(q.isEmpty());
- }
- }