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