java隊列

隊列是一種特殊的線性表,特殊之處在於它只允許在表的前端(front)進行刪除操作,而在表的後端(rear)進行插入操作,和棧一樣,隊列是一種操作受限制的線性表。進行插入操作的端稱爲隊尾,進行刪除操作的端稱爲隊頭。隊列中沒有元素時,稱爲空隊列。
在隊列這種數據結構中,最先插入的元素將是最先被刪除的元素;反之最後插入的元素將是最後被刪除的元素,因此隊列又稱爲“先進先出”(FIFO—first in first out)的線性表
對於順序隊列:
隊列空的條件:front=rear
隊列滿的條件: rear - front = MAXSIZE
對於循環隊列
隊列空的條件:front = rear
隊列滿的條件:front = ( rear+ 1) % MAXSIZE
/**
 * @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
發佈了117 篇原創文章 · 獲贊 2 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章