1.用两个栈实现队列
a栈用来存放加入的数
b栈用来存放要删除的数
当b栈存在数据时,就把top的元素pop掉
直到b栈中没有数据存放,再重新遍历a栈,把a的数据倒着遍历进b栈。也就是b栈存放着倒着的a栈数据,这样就可以防止重复。
以下是代码:
var CQueue = function() {
this.addStack = [];
this.deleteStack = [];
};
/**
* @param {number} value
* @return {void}
*/
CQueue.prototype.appendTail = function(value) {
this.addStack.push(value);
};
/**
* @return {number}
*/
CQueue.prototype.deleteHead = function() {
if(!this.deleteStack.length) {
while(this.addStack.length) {
this.deleteStack.push(this.addStack.pop());
}
}
return this.deleteStack.length? this.deleteStack.pop() : -1;
};
/**
* Your CQueue object will be instantiated and called as such:
* var obj = new CQueue()
* obj.appendTail(value)
* var param_2 = obj.deleteHead()
*/
2.最小栈:设置一个辅助栈,专门存放每一次push时候,整个数组的最小值。
/**
* initialize your data structure here.
*/
var MinStack = function() {
this.findMinStack = [];
this.saveStack = [];
};
/**
* @param {number} x
* @return {void}
*/
MinStack.prototype.push = function(x) {
this.saveStack.push(x);
if(this.findMinStack.length) {
if(x < this.findMinStack[this.findMinStack.length - 1]) {
this.findMinStack.push(x);
} else {
this.findMinStack.push( this.findMinStack[this.findMinStack.length - 1]);
}
} else {
this.findMinStack.push(x);
}
console.log('this.findMinStack',this.findMinStack)
};
/**
* @return {void}
*/
MinStack.prototype.pop = function() {
this.saveStack.pop();
this.findMinStack.pop();
};
/**
* @return {number}
*/
MinStack.prototype.top = function() {
return this.saveStack[this.saveStack.length - 1];
};
/**
* @return {number}
*/
MinStack.prototype.min = function() {
return this.findMinStack[this.findMinStack.length - 1];
// console.log('this.findMinStack',this.findMinStack);
};
/**
* Your MinStack object will be instantiated and called as such:
* var obj = new MinStack()
* obj.push(x)
* obj.pop()
* var param_3 = obj.top()
* var param_4 = obj.min()
*/