今日学习
理论基础
用栈实现队列
题目链接/文章讲解/视频讲解:https://programmercarl.com/0232.%E7%94%A8%E6%A0%88%E5%AE%9E%E7%8E%B0%E9%98%9F%E5%88%97.html
第一想法
这题主要考察的点在于要运用两个栈,一个入栈一个出栈。最关键的函数就是pop函数,pop函数要先考虑出栈中有没有元素,如果有直接弹出出栈的元素,如果没有那就依次取 入栈 的顶端元素push进出栈,再调用出栈的原始pop函数
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() {
if(this.stackOut.length) {
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
};
/**
* Your MyQueue object will be instantiated and called as such:
* var obj = new MyQueue()
* obj.push(x)
* var param_2 = obj.pop()
* var param_3 = obj.peek()
* var param_4 = obj.empty()
*/
用队列实现栈
题目链接/文章讲解/视频讲解:https://programmercarl.com/0225.%E7%94%A8%E9%98%9F%E5%88%97%E5%AE%9E%E7%8E%B0%E6%A0%88.html
与上题不同,本题可以用一个队列直接实现,pop就是将队列中queue.length-1个元素push到队列的后边,然后调用shift,取出第queue.length个元素
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 () {
const 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()
*/