队列的自定义实现

接口:

package com.heart.datastruc;
/**
 * 自定义队列
 * @author du.jian
 *
 */
public interface Queue<E> {
	/**
	 * 向队列尾部加入一个元素(入队)
	 * @return
	 */
	boolean add(E e);
	/**
	 * 删除队列头部元素(出队)
	 * @return
	 */
	E poll();
	/**
	 * 取队列头部元素;不删除
	 * @return
	 */
	E peek();
	/**
	 * 是否为空
	 */
	boolean empty();
}

实现:

package com.heart.datastruc;

import javax.swing.border.EmptyBorder;

public class QueueImpl<E> implements Queue<E> {
	
	private Object[] data = null;//池
	private int maxSize;//容量
	private int front;//队列头;只允许删除。
	private int rear;//队列尾;只允许插入。
	
	public QueueImpl() {//构造器。默认容量为16
		this(16);
	}

	public QueueImpl(int initSize) {
		if(initSize >=0) {
			this.maxSize = initSize;
			data = new Object[initSize];
			front = rear = 0;
		}else {
			throw new RuntimeException("The size can not less than 0: "+initSize);
		}
	}

	/**
	 * 向队列插入数据
	 */
	@Override
	public boolean add(E e) {
		if(rear == maxSize ) {
			throw new RuntimeException("Queue is full and cannot add");
		}else {
			data[rear++] = e;
			return true;
		}
	}

	/**
	 * 出队
	 */
	@Override
	public E poll() {
		if(empty()){
			throw new RuntimeException("Queue is empty!");
		}else {
			E value = (E) data[front];//临时保存队列front端的元素的值。
			data[front++] = null;//释放队列front端的元素。
			return value;
		}
	}

	/**
	 * 查头部元素。
	 */
	@Override
	public E peek() {
		if(empty()){
			throw new RuntimeException("Queue is empty!");
		}else {
			return (E) data[front];
		}
	}

	@Override
	public boolean empty() {
		return data.length ==0;
	}

}
发布了15 篇原创文章 · 获赞 2 · 访问量 4395

猜你喜欢

转载自blog.csdn.net/u012632105/article/details/103846355