循环队列的创建Java_循环队列的Java简单实现

基本概念

队列:一种先进先出(First In First Out,FIFO)的数据结构。其来自于我们日常生活中的排队问题,排在前面的先获得服务。

循环队列:长度固定的队列。其优势是循环利用内存资源,入队和出队都是O(1)的时间复杂度。通常,我们使用一个数组来实现循环队列,对头通过front指针标记,对尾通过tail指针标记。当front = tail时,队列为空;当tail + 1 = head时,队列为满。

基于这些约定,就可以编程实现循环队列了。

Java实现

抽象出队列接口。

/**

* A First In Fist Out (FIFO) data structure.

*

* @author Xingjian

* @since 2019/09/20

* @param element type

*/

public interface Queue {

/**

* add element to Queue.

*

* @param element

* @return true, element added successfully. Otherwise,false.

*/

boolean enQueue(T element);

/**

* get element from Queue.

*

* @return element, removed from Queue.Or null if Queue is empty.

*/

T deQueue();

/**

* test whether this Queue is empty.

*

* @return true, if Queue is empty. Otherwise,false.

*/

boolean isEmpty();

}

循环队列实现。

/**

* Circular Queue implementation.

*

* @author Xingjian

* @since 2019/09/20

* @param element type

*/

public class CircularQueue implements Queue {

/**

* element stored in this array.

*/

private T elements[];

/***

* front pointer.

*/

private int front;

/**

* tail pointer.

*/

private int tail;

/**

* construct a Circular Queue with given length.

*

* @param length

*/

@SuppressWarnings("unchecked")

public CircularQueue(int length) {

if (length <= 0) {

throw new IllegalArgumentException("length must be a positive integer.");

}

this.elements = (T[]) new Object[length];

this.front = 0;

this.tail = 0;

}

@Override

public boolean enQueue(T element) {

if ((tail + 1) % elements.length == front) {

// there is no space to add element.

return false;

}

elements[tail] = element;

tail = (tail + 1) % elements.length;

return true;

}

@Override

public T deQueue() {

if (isEmpty()) {

return null;

}

T e = elements[front];

front = (front + 1) % elements.length;

return e;

}

@Override

public boolean isEmpty() {

return front == tail;

}

}

标签:Java,队列,param,element,Queue,tail,循环,front

来源: https://blog.csdn.net/Tendency_Yang/article/details/101063847

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值