सर्कुलर क्यू
सर्कुलर क्यू एक रैखिक डेटा संरचना है जिसमें ऑपरेशन FIFO (फर्स्ट इन फर्स्ट आउट) सिद्धांत पर आधारित होते हैं और अंतिम स्थिति पहली स्थिति से जुड़ी होती है ताकि एक वृत्त बन सके। इसे "रिंग बफर" भी कहा जाता है।
सर्कुलर क्यू के लाभों में से एक यह है कि हम क्यू के सामने के स्थानों का उपयोग कर सकते हैं। एक सामान्य क्यू में, एक बार क्यू भर जाने पर, हम अगले तत्व को सम्मिलित नहीं कर सकते भले ही क्यू के सामने जगह हो। लेकिन सर्कुलर क्यू का उपयोग करके, हम नए मानों को संग्रहीत करने के लिए उस स्थान का उपयोग कर सकते हैं।
समस्या
हमें JavaScript में सर्कुलर क्यू के अपने कार्यान्वयन को डिज़ाइन करना है जो निम्नलिखित ऑपरेशन का समर्थन कर सके -
MyCircularQueue(k)- कंस्ट्रक्टर, क्यू का आकार k पर सेट करें।Front()- क्यू से फ्रंट आइटम प्राप्त करें। यदि क्यू खाली है, तो -1 वापस करें।Rear()- क्यू से अंतिम आइटम प्राप्त करें। यदि क्यू खाली है, तो -1 वापस करें।enQueue(value)- सर्कुलर क्यू में एक तत्व सम्मिलित करें। यदि ऑपरेशन सफल है तो true वापस करें।deQueue()- सर्कुलर क्यू से एक तत्व हटाएं। यदि ऑपरेशन सफल है तो true वापस करें।isEmpty()- जांचें कि सर्कुलर क्यू खाली है या नहीं।isFull()- जांचें कि सर्कुलर क्यू भरा हुआ है या नहीं।
उदाहरण
निम्नलिखित कोड है -
const CircularQueue = function(k) {
this.size = k;
this.queue = [];
this.start1 = 0;
this.end1 = 0;
this.start2 = 0;
this.end2 = 0;
};
CircularQueue.prototype.enQueue = function(value) {
if (this.isFull()) {
return false;
}
if (this.end2 <= this.size - 1) {
this.queue[this.end2++] = value;
} else {
this.queue[this.end1++] = value;
}
return true;
};
CircularQueue.prototype.deQueue = function() {
if (this.isEmpty()) {
return false;
}
if (this.queue[this.start2] !== undefined) {
this.queue[this.start2++] = undefined;
} else {
this.queue[this.start1++] = undefined;
}
return true;
};
CircularQueue.prototype.Front = function() {
if (this.isEmpty()) {
return -1;
}
return this.queue[this.start2] === undefined ? this.queue[this.start1] : this.queue[this.start2];
};
CircularQueue.prototype.Rear = function() {
if (this.isEmpty()) {
return -1;
}
return this.queue[this.end1 - 1] === undefined ? this.queue[this.end2 - 1] : this.queue[this.end1 - 1];
};
CircularQueue.prototype.isEmpty = function() {
if (this.end2 - this.start2 + this.end1 - this.start1 <= 0) {
return true;
}
return false;
};
CircularQueue.prototype.isFull = function() {
if (this.end2 - this.start2 + this.end1 - this.start1 >= this.size) {
return true;
}
return false;
};
const queue = new CircularQueue(2);
console.log(queue.enQueue(1));
console.log(queue.enQueue(2));
console.log(queue.enQueue(3));
console.log(queue.Rear());
console.log(queue.isFull());
console.log(queue.deQueue());
console.log(queue.enQueue(3));
console.log(queue.Rear());
आउटपुट
true true false 2 true true true 3