Without further ado, please refer to juejin.cn/post/703553…
This method, I think, is clear and easy to understand, with a bit of a twist on popMid and pushMid, but I’ve made it very clear that the idea of writing queues is very free and easy.
/* * @lc app=leetcode.cn id=1670 lang=javascript * * [1670] Design before, middle and after queue */
// @lc code=start
var FrontMiddleBackQueue = function () {
this.arr = [];
};
/ * * *@param {number} val
* @return {void}* /
FrontMiddleBackQueue.prototype.pushFront = function (val) {
this.arr.unshift(val)
};
/ * * *@param {number} val
* @return {void}* /
FrontMiddleBackQueue.prototype.pushMiddle = function (val) {
const midInx = Math.floor(this.arr.length / 2);
// array.splice( startIndex, deleteCount,item1,item2,... )
// Add val from minInx
this.arr.splice(midInx, 0, val)
};
/ * * *@param {number} val
* @return {void}* /
FrontMiddleBackQueue.prototype.pushBack = function (val) {
this.arr.push(val)
};
/ * * *@return {number}* /
FrontMiddleBackQueue.prototype.popFront = function () {
if (this.arr.length === 0) {
return -1;
}
return this.arr.shift()
};
/ * * *@return {number}* /
FrontMiddleBackQueue.prototype.popMiddle = function () {
if (this.arr.length === 0) {
return -1;
}
let midInx = Math.floor(this.arr.length / 2);
[1,2,3,4] midInx = 2
if (this.arr.length % 2= = =0) {
midInx--
}
return this.arr.splice(midInx, 1)};/ * * *@return {number}* /
FrontMiddleBackQueue.prototype.popBack = function () {
if (this.arr.length === 0) {
return -1;
}
return this.arr.pop()
};
/** * Your FrontMiddleBackQueue object will be instantiated and called as such: * var obj = new FrontMiddleBackQueue() * obj.pushFront(val) * obj.pushMiddle(val) * obj.pushBack(val) * var param_4 = obj.popFront() * var param_5 = obj.popMiddle() * var param_6 = obj.popBack() */
// @lc code=end
Copy the code