队列是一种特殊的
线性表,特殊之处在于它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作,和栈一样,队列是一种操作受限制的线性表。进行插入操作的端称为队尾,进行删除操作的端称为队头。队列中没有元素时,称为空队列。
对于顺序队列:
队列空的条件:front=rear
队列满的条件: rear - front = MAXSIZE
对于
循环队列:
队列空的条件:front = rear
队列满的条件:front = ( rear+ 1) % MAXSIZE
初始化 :0 0 0 0
添加数据 :2 0 0 1
添加数据 :2 3 4 3
删除后 :0 0 4 1
/**
* @Project: struts2
* @Title: Queue.java
* @Package com.yza.struct
* @author yongzhian
* @date 2014-10-8 下午3:51:44
* @Copyright: 2014 www.yineng.com.cn Inc. All rights reserved.
* @version V1.0
*/
package com.yza.struct;
/**
* @ClassName Queue
* @Description 队列
* @author yongzhian
* @Date 2014-10-8
*/
public class Queue {
public int maxSize; // 最大长度
public long[] queArray;
public int front;// 头
public int rear;// 尾
public int nItems;// 队列中的实际长度
public Queue(int s) // constructor构造器
{
maxSize = s;
queArray = new long[maxSize];
front = 0;
rear = -1;
nItems = 0;
}
// put item at rear of queue 从尾部插入数据
public void insert(long j) {
if (rear == maxSize - 1) {// deal with wraparound 处理边界值
rear = -1;// 已经溢出会把第一个值覆盖
}
queArray[++rear] = j; // increment rear and insert
nItems++; // one more item
}
public long remove() // take item from front of queue 从开始删除
{
long temp = queArray[front++]; // get value and incr front
queArray[(front-1)] = 0;
if (front == maxSize) { // deal with wraparound
front = 0;
}// 处理边界值 如果已经达到最大值则还原到第一个
nItems--; // one less item 项目数量减一个
return temp;
}
public long peekFront() // peek at front of queue 取得队列中第一个元素
{
return queArray[front];
}
public boolean isEmpty() // true if queue is empty
{
return (nItems == 0);
}
public boolean isFull() // true if queue is full
{
return (nItems == maxSize);
}
@Override
public String toString() {
String str = "";
for (int s = 0; s < maxSize; s++) {
str += queArray[s] + " ";
}
// TODO Auto-generated method stub
return str + " " + this.nItems;
}
public static void main(String[] args) {
Queue q = new Queue(3);
System.out.println(" 初始化 :" + q);
q.insert(2);
System.out.println(" 添加数据 :" + q);
q.insert(3);
q.insert(4);
System.out.println(" 添加数据 :" + q);
q.remove();q.remove();
System.out.println(" 删除后 :" + q);
}
}
打印输出:
初始化 :0 0 0 0
添加数据 :2 0 0 1
添加数据 :2 3 4 3
删除后 :0 0 4 1