Double-endian queue: A queue that allows us to add and remove elements from both the front end and the back end.
The following is a two-ended queue data structure that I encapsulated while learning about queues
Constructor () {this.item = {} this.count = 0 this.first = 0} Call addB() when the queue is empty to reduce code duplication If an element has been removed from the queue, the variable that records the first element should be subtracted by one before adding the element. The queue is not empty, the cut queue has never deleted an element before and then you have to move the original data back one, If (this.isempty ()) {this.addb (e)}else if(this.first > 0) {this.first-- this.item[this.first] = e }else { for(let i = this.count; i>0; i--) { this.item[i] = this.item[i-1] } this.count++ this.first = 0 this.item[0] = e } } addB(e) { this.item[this.count] = e this.count ++ } size() { return this.count - this.first } isEmpty() { return this.count - this.first === 0 } removeF() { if(this.isEmpty()) { return undefined } let res = this.item[this.first] delete this.item[this.first] this.first ++ return res } removeB() { if(this.isEmpty()) { return undefined }else { this.count-- let res = this.item[this.count] delete this.item[this.count] return res } } } var a = new Deque() console.log(a); a.addB('a') a.addB('b') a.addB('c') a.addF('d') a.removeF() console.log(a.item);Copy the code
This simply encapsulates a double-ended queue data structure. I’m using the object method to hold the data in the queue, or I can use an array to encapsulate the data. Reference Book: Learning JacaScript Data Structures and Algorithms (3rd edition)