ဒီတစ်ခေါက်ရဲ့ data structure ကတော့ Queue လို့ခေါ်တဲ့ linear data structure တစ်ခုဖြစ်ပါတယ်။ Stack နဲ့ ခပ်ဆင်ဆင်ဖြစ်ပြီးတော့ မတူတာကတော့ သူက First-in-First-out (FIFO) ဖြစ်ပြီးတော့ Stack ကတော့ FILO ဖြစ်တာပါ။ ဥပမာပေးရမယ်ဆိုရင်တော့ Queue data structure ဟာ လူတွေ restaurant တွေရဲ့ service counter မှာတန်းစီရတာနဲ့တူပါတယ်။ အရင်ရောက်တဲ့သူကို အရင်ဆုံး serve ရတာမျိုးပါ။ Queue မှာ Priority Queue လို့ခေါ်တဲ့ မူကွဲတစ်မျိုးလဲရှိပါသေးတယ်။ အဲဒါကဘယ်လိုမျိုးလဲဆိုတော့ ခုနက restaurant waiting line analogy နဲပဲ ပြန်ပြောရမယ်ဆိုလို့ရှိရင် VIP table ကိုအရင် serve ရတာမျိုးပါ။
Queue Applications
Queue ကို ကျနော်တို့ တခါထဲရှိသမျှ items တွေအကုန်လုံးကို process လုပ်စရာမလိုတဲ့အခြေအနေမျိုးမှာသုံးနိုင်ပါတယ်။ ဥပမာ e-commerce လိုမျိုးမှာဆိုရင် order list ကို implement လုပ်တဲ့နေရာမျိုးမှာသုံးနိုင်ပါတယ်။ အရင်ဝင်တဲ့ order ကို အရင် confirm လုပ် ၊ process လုပ် ၊ delivery လုပ်ရပါတယ်။ အကယ်၍ order တွေများနေလို့ရှိရင်လည်း pending လုပ်ရတာမျိုးရှိနိုင်ပါတယ်။ နောက်ပြီး VIP customer မျိုးဆိုလို့ရှိရင် ဦးစားပေးလုပ်ပေးရတာမျိုးရှိနိုင်တဲ့အတွက် ဒီလို e-commerce use case မျိုးမှာ Queue ဟာ ideal data structure ဖြစ်ပါတယ်။ ဒါ့အပြင် scheduling လုပ်ရတဲ့နေရာမျိုးတွေ ၊ asynchronous data transfer မျိုးတွေမှာလဲသုံးပါတယ်။
JavaScript Engine မှာ asynchronous operation တွေအတွက် Callback queue (သို့) Job queue လို့ခေါ်တဲ့ feature တစ်ခုရှိပါတယ်။ Call Stack ပေါ်ကိုပြန်ရောက်ဖို့အတွက် asynchronous operation တွေဟာ ဒီ Queue ထဲမှာ စောင့်နေကြရပါတယ်။
Operations in Queue
Queue မှာပါတဲ့ operations တွေကတော့ -
- Enqueue - queue ထဲကို item တစ်ခုထပ်ထည့်တာပါ။
- Dequeue - queue ထဲကနေ ရှေ့ဆုံး item ကိုထုတ်တာပါ။
Complexity
Time Complexity => O(1)
ဆိုတော့ Enqueue , Dequeue operation တွေဟာ constant time ဖြစ်ပါတယ်။
Implementation
Queue ကို Stack တုန်းကလိုပဲ Array နဲ့ဖြစ်ဖြစ် LinkedList နဲ့ဖြစ်ဖြစ် implement လုပ်လို့ရပါတယ်။ ဒီမှာတော့ ရှေ့မှာ Linked List လဲ implement လုပ်ခဲ့ပြီးတာဖြစ်တဲ့အတွက် Linked List ကိုသုံးပြီး implement လုပ်သွားပါမယ်။
// အရင် Article မှာတုန်းက implement လုပ်ခဲ့တဲ့ SinglyLinkedList ကိုပဲသုံးပါမယ်
const LinkedList = require('../LinkedList/SinglyLinkedList/singly.js')
class Queue {
constructor() {
this.items = new LinkedList()
}
isEmpty() {
// linked list ရဲ့ toArray method ကိုသုံးပြီး empty ဖြစ်မဖြစ်စစ်လို့ရပါတယ်
return this.items.toArray().length === 0
}
enqueue(item) {
// linked list ရဲ့ append ကိုသုံးနိုင်ပါတယ်
this.items.append(item)
}
dequeue() {
// linked list ရဲ့ head node ဟာ Queue ရဲ့ရှေ့ဆုံးက item ဖြစ်ပါတယ်
if (this.isEmpty()) {
throw new Error('Queue is empty!')
}
const item = this.items.head
this.items.delete(item.value)
return item.value
}
show() {
// ဒီမှာလဲ linked list က show method ကိုပဲပြန်သုံးထားတာပါ
return this.items.show()
}
}
module.exports = Queue
Conclusion
အပြင်လောကမှာလည်း တန်းစီတာ ၊ စောင့်ရတာစတဲ့ case မျိုးတွေဟာ အမြဲတစေတွေ့ရတာဖြစ်ပါတယ်။ Complexity အရလဲ efficient ဖြစ်တဲ့ Queue ဟာ ဒီလိုအရာတွေကို ထိန်းသိမ်းဖို့အတွက် အကောင်းဆုံးဖြစ်ပါတယ်။ ဒါ့ကြောင့် Queue ကို ခဏခဏ သုံးရဖို့အလားအလာများတာဖြစ်တဲ့အတွက် မရှိမဖြစ်သိထားသင့်တဲ့ data structure တစ်ခုဖြစ်ပါတယ်။