码迷,mamicode.com
首页 > 编程语言 > 详细

java数组实现队列

时间:2019-01-23 11:36:49      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:print   get   ati   system   false   als   ISE   bsp   bool   

 

package
Algorithm; /** * @author pujiahong2006@163.com</br> Created By: 2019-1-22 下午2:41:32 */ 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() { if (queue[tail] != null) {// exclude the inition status return tail % length == head;// tail++ when put } return false; } public boolean isEmpty() { if (queue[tail] != null) {// exclue the full status return false; } return tail == head;// head ++ when got } public int size() { if (isFull()) { return length; } if (isEmpty()) { return 0; } 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

 

java数组实现队列

标签:print   get   ati   system   false   als   ISE   bsp   bool   

原文地址:https://www.cnblogs.com/pu20065226/p/10307622.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!