隊列原理
- 隊列也是一種線性數據結構
- 相比數組來說,隊列對應的操作也是數組的子集
- 只能從一端(隊尾)添加元素,只能從另一端(隊首)取出元素
舉個例子,在超市買完東西結賬的時候需要排隊,當第一個人結賬的時候,也就是第一個元素,第一個人需要從排隊的欄杆的位置走到收銀員的位置,即是從隊尾進入隊列
。又來一個需要結賬的人,這個人也是從隊尾的位置進入隊列,排在第一個人的後面,依此類推。當收銀員已經結算好了第一個人,該處理第二個人的時候,這時第一個人離開收銀臺,即從隊首出列,此時隊列裏應該取出第一個元素,它與棧剛好相反。隊列是一種先進先出(FIFO)的的數據結構
隊列的實現
Queue<E>
void enqueue(E) // 入隊
E dequeue() // 出隊
E getFront() // 查看隊首
int getSize() // 查看大小
boolean isEmpty() // 是否爲空
用戶不關心隊列底層的實現,可以設計一個接口Interface Queue<E>
,依託不同的底層的數據結構來實現這個接口,複用Array
動態數組類,來實現一個屬於自己的ArrayQueue<E>
。
1.定義接口
文件名文Queue.java
// 隊列接口依舊支持泛型
public interface Queue<E> {
void enqueue(E e); // 入隊
E dequeue(); // 出隊
E getFront(); // 查看隊首
int getSize(); // 查看大小
boolean isEmpty(); // 是否爲空
}
2.複用動態數組Array
Array.java是我在另一篇文《創建一個屬於自己的數組類》中實現的動態數組,在這裏採用通過數組的方式來實現隊列,代碼拿來複用。
public class Array<E> {
private E[] data;
private int size;
// 構造函數,傳入數組的容量capacity構造Array
public Array(int capacity){
data = (E[])new Object[capacity];
size = 0;
}
// 無參數的構造函數,默認數組的容量capacity=10
public Array(){
this(10);
}
// 獲取數組的容量
public int getCapacity(){
return data.length;
}
// 獲取數組中的元素個數
public int getSize(){
return size;
}
// 返回數組是否爲空
public boolean isEmpty(){
return size == 0;
}
// 在index索引的位置插入一個新元素e
public void add(int index, E e){
if(index < 0 || index > size)
throw new IllegalArgumentException("Add failed. Require index >= 0 and index <= size.");
if(size == data.length)
resize(2 * data.length);
for(int i = size - 1; i >= index ; i --)
data[i + 1] = data[i];
data[index] = e;
size ++;
}
// 向所有元素後添加一個新元素
public void addLast(E e){
add(size, e);
}
// 在所有元素前添加一個新元素
public void addFirst(E e){
add(0, e);
}
// 獲取index索引位置的元素
public E get(int index){
if(index < 0 || index >= size)
throw new IllegalArgumentException("Get failed. Index is illegal.");
return data[index];
}
public E getLast(){
return get(size - 1);
}
public E getFirst(){
return get(0);
}
// 修改index索引位置的元素爲e
public void set(int index, E e){
if(index < 0 || index >= size)
throw new IllegalArgumentException("Set failed. Index is illegal.");
data[index] = e;
}
// 查找數組中是否有元素e
public boolean contains(E e){
for(int i = 0 ; i < size ; i ++){
if(data[i].equals(e))
return true;
}
return false;
}
// 查找數組中元素e所在的索引,如果不存在元素e,則返回-1
public int find(E e){
for(int i = 0 ; i < size ; i ++){
if(data[i].equals(e))
return i;
}
return -1;
}
// 從數組中刪除index位置的元素, 返回刪除的元素
public E remove(int index){
if(index < 0 || index >= size)
throw new IllegalArgumentException("Remove failed. Index is illegal.");
E ret = data[index];
for(int i = index + 1 ; i < size ; i ++)
data[i - 1] = data[i];
size --;
data[size] = null; // loitering objects != memory leak
if(size == data.length / 4 && data.length / 2 != 0)
resize(data.length / 2);
return ret;
}
// 從數組中刪除第一個元素, 返回刪除的元素
public E removeFirst(){
return remove(0);
}
// 從數組中刪除最後一個元素, 返回刪除的元素
public E removeLast(){
return remove(size - 1);
}
// 從數組中刪除元素e
public void removeElement(E e){
int index = find(e);
if(index != -1)
remove(index);
}
@Override
public String toString(){
StringBuilder res = new StringBuilder();
res.append(String.format("Array: size = %d , capacity = %d\n", size, data.length));
res.append('[');
for(int i = 0 ; i < size ; i ++){
res.append(data[i]);
if(i != size - 1)
res.append(", ");
}
res.append(']');
return res.toString();
}
// 將數組空間的容量變成newCapacity大小
private void resize(int newCapacity){
E[] newData = (E[])new Object[newCapacity];
for(int i = 0 ; i < size ; i ++)
newData[i] = data[i];
data = newData;
}
}
3.隊列的實現
通過實現接口,調用Array.java來實現隊列。
ArrayQueue.java
public class ArrayQueue<E> implements Queue<E> {
private Array<E> array;
// 構造函數,可以讓用戶傳進來一個容基
public ArrayQueue(int capacity) {
array = new Array<>(capacity);
}
// 構造函數,不傳參數
public ArrayQueue() {
array = new Array<>();
}
@Override
public int getSize() {
// 直接返回數組的大小
return array.getSize();
}
@Override
public boolean isEmpty() {
return array.isEmpty();
}
public int getCapacity() {
return array.getCapacity();
}
// 向隊列中添加元素
@Override
public void enqueue(E e) {
// 像數組的末尾添加元素即像隊列中添加,從末尾開始
array.addLast(e);
}
@Override
public E dequeue() {
// 從隊首取出元素,即刪除數組的第一個元素
// 取出前需要判斷isEmpty(),動態數組中也已經實現
// 可能會觸發一些動態數組的縮容,不需要管,在動態數組中已經實現過
return array.removeFirst();
}
// 查看隊首是誰
@Override
public E getFront() {
return array.getFirst();
}
@Override
public String toString() {
StringBuilder res = new StringBuilder();
res.append("Queue:");
// 在打印輸出的時候顯示告訴用戶隊首的位置
res.append("front[");
for (int i = 0; i < array.getSize(); i++) {
// 將array的每一個元素都添加到res中
res.append(array.get(i));
// 如果i不是最後一個元素,逗號隔開 getSize()獲取元素中的個數
if (i != array.getSize() - 1) {
res.append(", ");
}
}
// 循環結束加上"]" 標註一個tail表示隊列的末尾
res.append("]tail");
return res.toString();
}
}
4.編寫Main進行隊列測試
爲了更加方便的直觀看到隊列的先進先出,在for循環中加入了進三出一
的邏輯。
Main.java
public class Main {
public static void main(String[] args) {
ArrayQueue<Integer> queue = new ArrayQueue<>();
// 入列測試
for (int i = 0; i < 10; i++) {
queue.enqueue(i);
System.out.println(queue);
// 往隊列中每插入三個元素,就取出一個元素
if (i % 3 == 2) {
queue.dequeue();
System.out.println(queue);
}
}
}
}
5.結果分析
根據結果可以直觀的看到,往隊列中依次添加0-9這10個元素,遵循進三出一
的邏輯。
- 當
“0,1,2”
依次入列,從隊首取出一個元素,0先出列
。 - 接着
“3,4,5”
依次入列,這時從隊首取出一個元素1出列
。 “6,7,8”
依次入列,從隊首取出一個元素2出列
。“9”
入列,循環終止,這是隊列中的元素只剩下“3,4,5,6,7,8,9”
這7個元素。
Queue:front[0]tail
Queue:front[0, 1]tail
Queue:front[0, 1, 2]tail
Queue:front[1, 2]tail
Queue:front[1, 2, 3]tail
Queue:front[1, 2, 3, 4]tail
Queue:front[1, 2, 3, 4, 5]tail
Queue:front[2, 3, 4, 5]tail
Queue:front[2, 3, 4, 5, 6]tail
Queue:front[2, 3, 4, 5, 6, 7]tail
Queue:front[2, 3, 4, 5, 6, 7, 8]tail
Queue:front[3, 4, 5, 6, 7, 8]tail
Queue:front[3, 4, 5, 6, 7, 8, 9]tail
寫在最後
如果代碼有還沒有看懂的或者我寫錯的地方,歡迎評論,我們一起學習討論,共同進步。
推薦學習地址:
liuyubobobo老師的《玩轉數據結構》:https://coding.imooc.com/class/207.html
最後,祝自己早日鹹魚翻身,拿到心儀的Offer,衝呀!