1、前言
數據結構,是計算機編程中對數據存儲最基本的操作,不同的數據結構適用不同的業務場景。如今大部分情況都是調用開發API封裝好的類庫,直接調用,幾乎不需要程序員再去深究其中背后實現的邏輯,大大簡化和減低了對程序員的要求。正是這種,知其然而不知其所以然,導致很多程序員缺乏對於底層結構的了解,分不清楚不同數據結構之間的性能差異,導致出現很多系統性能問題。
2、原理推導
隊列的應用,隊列是一種特殊的線性表,在隊列尾部一端插入數據或在隊列頭部一端刪除數據,遵循"先進先出"(FIFO)原則。
隊列在具體的應用過程中又分為循環隊列,雙端隊列,優先級隊列。這里以循環隊列為例,實現隊列簡單的插入和移除操作。
#說明
循環隊列,是隊列中如果有移除操作,為了避免隊列存儲有空位,卻不能插入新數據項的問題,讓尾部的指針重新回到數組開始的位置存儲,這就是循環隊列,也稱為緩沖環。
3、代碼示例
# 循環隊列的基本操作
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();
}
}
4、禪定時刻
隊列的應用,主要是利用先入先出的特性,解決一些具體業務場景比如多系統之間消息通知,訂單處理,日志系統等,涉及到需要異步處理,應用解耦,流量削鋒和消息通訊四個場景。
作者簡介
思維的持續,一個真的有思想,不穿格子襯衫的程序員。