解題思路
- 使用兩個(gè)數(shù)組的棧方法
push
和 pop
實(shí)現(xiàn)隊(duì)列,分別定義為輸入棧和輸出棧袱瓮。
- 輸出棧主要用來(lái)彈出元素的時(shí)候之宿,逆轉(zhuǎn)輸入棧元素的順序磁玉,然后彈出,來(lái)實(shí)現(xiàn)隊(duì)列的先入先出特點(diǎn)中鼠。
- 注意彈出元素時(shí)可婶,如果輸出棧為空,需要將輸入棧全部的元素加入到輸出棧中援雇。
var MyQueue = function() {
this.stackIn = []; // 輸入棧
this.stackOut = []; // 輸出棧
};
/**
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function(x) {
this.stackIn.push(x);
};
/**
* @return {number}
*/
MyQueue.prototype.pop = function() {
let size = this.stackOut.length;
if (size) {
return this.stackOut.pop()
}
while (this.stackIn.length) {
this.stackOut.push(this.stackIn.pop())
}
return this.stackOut.pop()
};
/**
* @return {number}
*/
MyQueue.prototype.peek = function() {
const x = this.pop()
this.stackOut.push(x);
return x;
};
/**
* @return {boolean}
*/
MyQueue.prototype.empty = function() {
return !(this.stackIn.length || this.stackOut.length)
};
解題思路
- 利用隊(duì)列模擬棧的行為矛渴,比如存在隊(duì)列
[1,2,3,4]
,那么作為棧彈出時(shí)熊杨,應(yīng)該優(yōu)先彈出 4
曙旭。
- 除去最后一個(gè)元素,將剩余
0 ~ (length - 1)
的元素依次加入至末尾晶府,即可桂躏。
var MyStack = function() {
this.queue = []
};
/**
* @param {number} x
* @return {void}
*/
MyStack.prototype.push = function(x) {
this.queue.push(x)
};
/**
* @return {number}
*/
MyStack.prototype.pop = function() {
let size = this.queue.length
while (size-- > 1) {
this.queue.push(this.queue.shift())
}
return this.queue.shift()
};
/**
* @return {number}
*/
MyStack.prototype.top = function() {
let x = this.pop()
this.queue.push(x)
return x
};
/**
* @return {boolean}
*/
MyStack.prototype.empty = function() {
return !this.queue.length
};
/**
* Your MyStack object will be instantiated and called as such:
* var obj = new MyStack()
* obj.push(x)
* var param_2 = obj.pop()
* var param_3 = obj.top()
* var param_4 = obj.empty()
*/