232 用栈实现队列
可以使用两个栈,一个用于push,另一个用于pop。在push的时候,我们只在1push,pop的时候把1中的所有pop出来,push到2中,这样可以确保2里的顺序是先加入的元素在顶端。
var MyQueue = function () {
this.stack1 = []
this.stack2 = []
};
/**
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function (x) {
this.stack1.push(x)
};
/**
* @return {number}
*/
MyQueue.prototype.pop = function () {
if (this.stack2.length > 0) {
return this.stack2.pop()
}
while (this.stack1.length > 0) {
const el = this.stack1.pop()
this.stack2.push(el)
}
return this.stack2.pop()
};
/**
* @return {number}
*/
MyQueue.prototype.peek = function () {
if (this.stack2.length > 0) {
return this.stack2[this.stack2.length - 1]
}
while (this.stack1.length > 0) {
const el = this.stack1.pop()
this.stack2.push(el)
}
return this.stack2[this.stack2.length - 1]
};
/**
* @return {boolean}
*/
MyQueue.prototype.empty = function () {
return this.stack1.length === 0 && this.stack2.length === 0
};
225 用队列实现栈
使用两个队列,每一次pop把队列除了最后一个都放到下一个队列中,应该可以用一个队列当成环来解决。
var MyStack = function() {
this.q1 = []
this.q2 = []
};
/**
* @param {number} x
* @return {void}
*/
MyStack.prototype.push = function(x) {
if (this.q1.length === 0 && this.q2.length === 0) {
this.q1.push(x)
} else if (this.q1.length === 0) {
this.q2.push(x)
} else {
this.q1.push(x)
}
};
/**
* @return {number}
*/
MyStack.prototype.pop = function() {
if (this.q1.length === 0) {
while (this.q2.length > 1) {
const el = this.q2.shift()
this.q1.push(el)
}
return this.q2.shift()
} else {
while (this.q1.length > 1) {
const el = this.q1.shift()
this.q2.push(el)
}
return this.q1.shift()
}
};
/**
* @return {number}
*/
MyStack.prototype.top = function() {
if (this.q1.length === 0) {
while (this.q2.length > 1) {
const el = this.q2.shift()
this.q1.push(el)
}
const el2 = this.q2.shift()
this.q1.push(el2)
return el2
} else {
while (this.q1.length > 1) {
const el = this.q1.shift()
this.q2.push(el)
}
const el2 = this.q1.shift()
this.q2.push(el2)
return el2
}
};
/**
* @return {boolean}
*/
MyStack.prototype.empty = function() {
return this.q1.length === 0 && this.q2.length === 0
};