队列的自定义实现

接口:

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;
	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值