数组队列

用数组实现的队列,也叫循环队列。就是定义一个数组,用两个下标head,tail表示队头和队尾。当队头和队尾相等时,队列为空。当队尾+1等于队头时,队列为满。

注意tail的值,当插入一个元素时tail=1 szie=1,两个时tail=2 size=2,三个时tail=0 size=3,四个时报错“is full”

package Algorithm;

public class QueueByArray {
private Object[] queue;
final static int DEFAULT_MAX_SIZE = 100;
int length, head, tail; private void init() {
queue = new Object[length];
head = tail = 0;
} QueueByArray() {
length = DEFAULT_MAX_SIZE;
init();
} QueueByArray(int size) {
length = size;
init();
} public boolean isFull() {
return size() == length; } public boolean isEmpty() {
return size() == 0;
} public int size() {
if (queue[tail] != null && tail == head) {
return length;
} return (tail - head + length) % length;
} public void clear() {
queue = null;
queue = new Object[length];
} // in queue
public void put(Object o) throws Exception {
if (isFull()) {
System.out.println(head);
System.out.println(tail);
throw new Exception("the queue is full!");
} else {
queue[tail] = o;
tail = (tail + 1) % length;
}
} // out queue
public Object get() throws Exception {
if (isEmpty()) {
throw new Exception("the queue is empty!");
} else {
final Object o = queue[head];
queue[head] = null;
head = (head + 1) % length;
return o;
}
} public static void main(String[] args) throws Exception {
final QueueByArray myqueue = new QueueByArray(3); for (int i = 111; i < 114; i++) {
myqueue.put(i);
}
System.out.println("head==" + myqueue.head + ";tail==" + myqueue.tail + ";size=="
+ myqueue.size()); while (myqueue.size() > 0) {
System.out.println(myqueue.get());
} } }

输出:

head==0;tail==0;size==3
111
112
113

最新文章

  1. telent对端口检测状态分析
  2. pm2.5检测统计
  3. node.js基础 1之 HTTP流程实例
  4. 全面分析Java的垃圾回收机制
  5. 图的割点 | | jzoj【P1230】 | | gdoi | |备用交换机
  6. 提取c#代码文件中的方法块
  7. [转] ubuntu开启SSH服务
  8. JAVA通过XPath解析XML性能比较(原创)
  9. C#并行编程--命令式数据并行(Parallel.Invoke)---与匿名函数一起理解(转载整理)
  10. PLSQL_性能优化工具系列10_Automatic Database Diagnostic Monitor - ADDM
  11. LINQ to XML LINQ学习第一篇
  12. Objective-C对象模型及应用
  13. javaWeb学习总结(10)- EL函数库(2)
  14. R+tmcn笔记︱tmcn包的基本内容以及李舰老师R语言大会展示内容摘录
  15. vue小技巧之偷懒的文件路径——减少不必要的代码
  16. Unity中用Mono插件解析xml文件
  17. ecplise的Jsp红叉错误消除
  18. git权限
  19. 腾讯云服务器 设置ngxin + fastdfs +tomcat 开机自启动
  20. zookeeper和Eureka对CAP理论的支持

热门文章

  1. 【Nginx】之安装使用和配置SSL支持
  2. VMware中四种网络连接模式的区别
  3. problem:为什么会有options请求
  4. elasticsearch 安装(基于java运行环境)
  5. static--Android静态变量使用陷阱
  6. F5负载均衡原理(转载)
  7. MySQL客户端管理
  8. 光伏电池测控系统python代码
  9. Java并发知识整理
  10. JVM总结-java内存模型