[size=medium]简介[/size]
队列是一种特殊的线性表,它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作。进行插入操作的端称为队尾,进行删除操作的端称为队头。队列中没有元素时,称为空队列。
在队列这种数据结构中,最先插入的元素将是最先被删除的元素;反之最后插入的元素将最后被删除的元素,因此队列又称为“先进先出”(FIFO—first in first out)的线性表。
队列空的条件: front=rear
队列满的条件: rear = MAXSIZE
队列是一种特殊的线性表,它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作。进行插入操作的端称为队尾,进行删除操作的端称为队头。队列中没有元素时,称为空队列。
在队列这种数据结构中,最先插入的元素将是最先被删除的元素;反之最后插入的元素将最后被删除的元素,因此队列又称为“先进先出”(FIFO—first in first out)的线性表。
队列空的条件: front=rear
队列满的条件: rear = MAXSIZE
/**
* simulate queue struct by java
*
* @author Bruce
* @date Sep 8, 2011
* @version 1.0
*/
public class Queue {
private int maxSize;
private long[] queueArray;
private int front;// the head of queue
private int rear;// the end of queue
private int nItems;
/**
* Constructor a queue,the size is s;now the queue is null, and the front is
* zero and the rear is negative one
*
* @param s
*/
public Queue(int s) {
maxSize = s;
queueArray = new long[maxSize];
front = 0;
rear = 0;
nItems = 0;
}
public void insert(long j) {
// if the the inserted items great the size of queue,
// the rear return the initial value and the next item will
// override the corresponding value
if (rear == maxSize)
rear = 0;
queueArray[rear++] = j;
nItems++;// the count of the items
}
/**
* remove the item from the 'front' position,every time the front will be
* added one
*/
public long remove() {
long temp = queueArray[front++];
// if the front equals the size of queue,the front will return the
// initial value
if (front == maxSize)
front = 0;
nItems--;
if (nItems < 0)
nItems = 0;
return temp;
}
public long peekFront() {
return queueArray[front];
}
public boolean isEmpty() {
return (nItems == 0);
}
public boolean isFull() {
return (nItems == maxSize);
}
public int size() {
return nItems;
}
public static void main(String[] args) {
Queue queue = new Queue(3);
queue.insert(3);
queue.insert(6);
queue.insert(8);
// queue.insert(4);
System.out.println("size:" + queue.size());
System.out.println(queue.peekFront());
queue.remove();
System.out.println(queue.peekFront());
queue.remove();
System.out.println(queue.peekFront());
queue.remove();
// System.out.println(queue.peekFront());
// queue.remove();
System.out.println("size:" + queue.size());
}
}