用栈实现队列
题目链接:用栈实现队列
var MyQueue = function() {
this.stackIn = []
this.stackOut = []
};
MyQueue.prototype.push = function(x) {
this.stackIn.push(x)
};
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()
};
MyQueue.prototype.peek = function() {
const node = this.pop()
this.stackOut.push(node)
return node
};
MyQueue.prototype.empty = function() {
return !this.stackIn.length && !this.stackOut.length
};
用队列实现栈
题目链接:用队列实现栈
var MyStack = function() {
this.queue = []
};
MyStack.prototype.push = function(x) {
this.queue.push(x)
};
MyStack.prototype.pop = function() {
return this.queue.pop()
};
MyStack.prototype.top = function() {
const node = this.pop()
this.push(node)
return node
};
MyStack.prototype.empty = function() {
return !this.queue.length
};