JS 对太友好了,如果想体会原汁原味的栈(先进后出),那就不要在栈底操作元素,比如使用
shift()
方法,而且排序也不要调用 API
排序栈(中等)
- 思路:辅助栈
- 每次要取最小元素,那意味着在取的时候排序?思考一会便知道不现实——题目要求顶多两个栈,如果存数据的栈里面是乱序,至少得三个栈才能完成排序
- 所以可以计划在存数据时就进行排序,你会发现两个栈足够了。每当存入一个数
val
,就与栈顶的数top
做比较,如果val
大,就把top
取出放入辅助栈,如果val
小,就直接存入(维持最小值在栈顶) - 最后一步在把辅助栈的元素存回数据栈就好(怎么出来怎么回去),其他步骤都是小case了
var SortedStack = function() {
this.stack = []
this.copy = [] // 辅助栈
};
SortedStack.prototype.push = function(val) {
// 数据栈不为空且栈顶小于val
while (this.stack.length && this.stack[this.stack.length - 1] < val) {
this.copy.push(this.stack.pop())
}
this.stack.push(val) // 在合适的位置存入val
// 把辅助栈的元素倒入数据栈
while (this.copy.length) {
this.stack.push(this.copy.pop())
}
};
SortedStack.prototype.pop = function() {
this.stack.length && this.stack.pop()
};
SortedStack.prototype.peek = function() {
return this.stack.length === 0 ? -1 : this.stack[this.stack.length - 1]
};
SortedStack.prototype.isEmpty = function() {
return this.stack.length === 0 ? true : false
};
最小栈(简单)
- 思路:一个数据栈加一个辅助栈,每当数据栈加入元素时,辅助栈也加入元素,该元素为数据栈中此时对应的最小值。比如数据栈加入1,辅助栈加入1,数据栈加入2,辅助栈还是加入1,当数据栈栈顶元素被取出时辅助栈栈顶元素也取出,所以辅助栈中永远保存着当前的最小值
var MinStack = function() {
this.stack = []
this.help = []
};
MinStack.prototype.push = function(val) {
if (!this.stack.length) {
this.help.push(val)
} else {
let top = this.help[this.help.length - 1]
top > val ? this.help.push(val) : this.help.push(top)
}
this.stack.push(val)
};
MinStack.prototype.pop = function() {
this.stack.pop()
this.help.pop()
};
MinStack.prototype.top = function() {
return this.stack[this.stack.length - 1]
};
MinStack.prototype.getMin = function() {
return this.help[this.help.length - 1]
};
用队列实现栈(简单)
- 思路:关键点在于
push
部分的实现,要用两个队列的先进先出来模拟一个栈的先进后出
var MyStack = function() {
this.queue1 = []
this.queue2 = []
};
MyStack.prototype.push = function(x) {
this.queue2.push(x);
while (this.queue1.length) this.queue2.push(this.queue1.shift());
[this.queue1, this.queue2] = [this.queue2, this.queue1];
};
MyStack.prototype.pop = function() {
return this.queue1.shift()
};
MyStack.prototype.top = function() {
return this.queue1[0]
};
MyStack.prototype.empty = function() {
if (this.queue1.length) {
return false
} else {
return true
}
};
如果觉得对你有帮助的话,点个赞呗~
反正发文又不赚钱,交个朋友呗~
如需转载,请注明出处foolBirdd