`

Java数组队列ArrayQueue

阅读更多

  队列是一种“FIFO”先进先出的数据结构.可以想象每年在火车站中买票的人群所组成的"队列"。

  |队员1 队员2 队员3 队员3 队员4 队员5 队员6 队员7 队员8|

     ^                                                                     ^

    想象两个指针 一个指向队头 一个指向队尾,加人到队列中是从队尾入的,出队是从队头出队的。 

队列接口:

 

    

/**
 * 队列FIFO的接口
 * 
 * @author 鼎鼎
 * 
 * @param <E>
 */
public interface Queue<E> {

	/**
	 * 入队: 从队尾加入一元素
	 * 
	 * @param target
	 */
	public void add(E target);

	/**
	 * 出队: 移走队头元素
	 * 
	 * @param target
	 * @return 当前队头元素
	 */
	public E remove();

	/**
	 * 当前队列中的元素个数
	 */
	public int size();

	/**
	 * 判断当前队列是否为空
	 * 
	 * @return
	 */

	public boolean isEmpty();
	/**
	 * 只是返回队头元素
	 * @return
	 */
	public E front();

}

 数组队列的代码实现:

 

     

public class ArrayQueue<E> implements Queue<E> {

	private E[] data;

	// 当前队列中元素的大小
	private int size;

	private int front;

	private int rear;

	public ArrayQueue() {
		data = (E[]) new Object[20];
		size = 0;
		front = 0;
		rear = 0;
	}

	public void add(E target) {
		if (isFull()) {
			
			enlarge();
	     //数组队列满后,需要扩充,记住扩充后要将front的值归0
			front=0;
		}
	
		rear = (front + size) % data.length;
		
		data[rear] = target;

		size++;
	}

	public boolean isEmpty() {

		return size == 0;
	}

	/**
	 * 判断当前队列是否已满
	 * 
	 * @return
	 */
	public boolean isFull() {

		return size == data.length;

	}

	/**
	 * 将数组容量扩大两倍
	 * 
	 */
	public void enlarge() {
		E[] newData = (E[]) new Object[data.length * 2];
		for (int i = 0; i < data.length; i++) {
			newData[i] = data[i];

		}
		data = newData;
		newData = null;
	
	
		
	}

	public E remove() {
		if (isEmpty()) {
	   
			throw new RuntimeException("队列为空!");
		}
	
		E tempData = data[front];
	
		
		data[front] = null;
		front = (front + 1) % (data.length);
	
		size--;

		return tempData;
	}

	public int size() {

		return size;
	}

	public E front() {
		if (isEmpty()) {

			throw new RuntimeException("队列为空!");
		}
		return data[front];
	}

}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics