/**
* @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