数据结构,是计算机编程中对数据存储最基本的操作,不同的数据结构适用不同的业务场景。如今大部分情况都是调用开发API封装好的类库,直接调用,几乎不需要程序员再去深究其中背后实现的逻辑,大大简化和减低了对程序员的要求。正是这种,知其然而不知其所以然,导致很多程序员缺乏对于底层结构的了解,分不清楚不同数据结构之间的性能差异,导致出现很多系统性能问题。
队列的应用,队列是一种特殊的线性表,在队列尾部一端插入数据或在队列头部一端删除数据,遵循"先进先出"(FIFO)原则。
队列在具体的应用过程中又分为循环队列,双端队列,优先级队列。这里以循环队列为例,实现队列简单的插入和移除操作。
循环队列,是队列中如果有移除操作,为了避免队列存储有空位,却不能插入新数据项的问题,让尾部的指针重新回到数组开始的位置存储,这就是循环队列,也称为缓冲环。
# 循环队列的基本操作
public class BaseQueue {
/**
* 存放队列数组
*/
private int [] queueArray;
/**
* 队列起始索引位置
*/
private int frontIndex;
/**
* 队列结束索引位置
*/
private int endIndex;
/**
* 队列中元素数量
*/
private int sumTotal;
public BaseQueue(int length){
queueArray = new int[length];
frontIndex = 0;
endIndex = -1;
sumTotal = 0;
}
/**
* 数据循环插入队列
* @param data
*/
public void insertQueue(int data){
// 如果队列中有移除操作,为了避免队列不满,让尾部指针回到数组开始位置,形成循环队列,节省队列空间
if (endIndex == queueArray.length - 1){
endIndex = -1;
}
endIndex++;
queueArray[endIndex] = data;
sumTotal++;
// 如果队列计数值大于队列实际长度,则重置队列计数值
if (sumTotal > queueArray.length){
sumTotal = queueArray.length;
}
}
/**
* 移除队列中的数据
* @return
*/
public int removeQueue(){
// 如果队列中没有数据,直接返回,不需移除操作
if (sumTotal == 0){
return 0;
}
//清空队列当前索引的数据
int data = queueArray[frontIndex];
queueArray[frontIndex] = 0;
// 如果队列中已经是最后一个数,则单独再执行移除操作
if (frontIndex == queueArray.length - 1){
frontIndex = 0;
}
frontIndex++; // 每一次移除操作,索引位置往后移位
sumTotal--; // 每一次移除操作,队列中总数递减
return data;
}
/**
* 查看当前索引位置数据
* @return
*/
public int peekFront(){
return queueArray[frontIndex];
}
/**
* 打印队列中的所以数据
*/
public void printQueue(){
System.out.println("-----思维的持续-----");
for (int data:queueArray){
System.out.println(data);
}
}
public static void main(String[] args) {
BaseQueue baseQueue = new BaseQueue(5);
baseQueue.insertQueue(3);
baseQueue.insertQueue(4);
baseQueue.insertQueue(5);
baseQueue.insertQueue(6);
baseQueue.insertQueue(7);
baseQueue.printQueue();
int result1 = baseQueue.peekFront();
System.out.println("-----result1-----"+result1);
baseQueue.removeQueue();
int result2 = baseQueue.removeQueue();
System.out.println("-----result2-----"+result2);
baseQueue.printQueue();
baseQueue.insertQueue(8);
baseQueue.insertQueue(9);
baseQueue.printQueue();
}
}
队列的应用,主要是利用先入先出的特性,解决一些具体业务场景比如多系统之间消息通知,订单处理,日志系统等,涉及到需要异步处理,应用解耦,流量削锋和消息通讯四个场景。
原文:https://www.cnblogs.com/swdcx/p/12527597.html