入列出列java,队列java实现

队列和栈相反,是先进先出(FIFO,first in first out)的数据集合。就跟排队打饭一样,最先进入队伍的总是最先离开。

队列元素的操作一般由入列(enQueue)和出列(deQueue)组成。 按照通常理解,如果队首的人离开,队伍中所有的人将往前挪一个位置,在下面的代码里,我没有这么做,因为如果每次出列都进行一次平移,就造成了多次元素交换,影响效率,当然如果你不在乎可以进行平移。取而代之的是,用两个索引head跟tail来标记当前队首跟队尾元素的索引,避免了移位。在这里,没有实现队列的自动增长,使用索引来标记队首队尾元素,增加了自动增长的难度,其实也很简单,只是暂时觉得没有必要实现。

package cangzhitao.com.algorithms.datastructure;

import cangzhitao.com.algorithms.datastructure.exception.QueueOverFlowException;

/**

* 队列,不支持自动增长

* @author lihui

*

*/

public class Queue {

private T[] arrays;

/**

* 队列容量

*/

private int capacity = 10;

/**

* 初始化数组

* @param capacity

* @return 泛型数组

*/

@SuppressWarnings("unchecked")

private T[] initArray(int capacity) {

return (T[]) new Object[capacity];

}

public Queue() {

arrays = initArray(capacity);

}

public Queue(int capacity) {

this.capacity = capacity;

arrays = initArray(capacity);

}

/**

* 当前队列第一个元素的位置

*/

private int head = 0;

/**

* 当前队列最后一个元素的位置

*/

private int tail = -1;

/**

* 队列中的元素个数

*/

private int size = 0;

public boolean isFull() {

if(size==capacity) {

return true;

} else {

return false;

}

}

public boolean isEmpty() {

if(size==0) {

return true;

} else {

return false;

}

}

/**

* 入列

* @param o

* @return

*/

public Queue enQueue(T o) {

boolean isFull = isFull();

if(isFull) {

throw new QueueOverFlowException("队列已满");

}

if(tail

tail++;

} else {

tail = 0;

}

size ++;

arrays[tail] = o;

return this;

}

/**

* 出列

* @return

*/

public T deQueue() {

boolean isEmpty = isEmpty();

if(isEmpty) {

throw new QueueOverFlowException("队列已空");

}

T o = arrays[head];

arrays[head] = null;

if(head

head++;

} else {

head = 0;

}

size --;

return o;

}

/**

* @param args

*/

public static void main(String[] args) {

Queue q = new Queue(5);

q.enQueue(1);

q.enQueue(2);

q.enQueue(3);

q.enQueue(4);

q.enQueue(5);

q.deQueue();

q.enQueue(6);

q.deQueue();

q.enQueue(7);

while(!q.isEmpty()) {

System.out.println(q.deQueue());

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值