1、用两个栈实现队列
- 用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
用数组模拟栈后进先出,就只能使用数组的pop和push方法了
js初始化定义数组
//定义一个长度为40,且初始值为0的数组
var arry=new Arry(40).fill(0)
stack1专门用来进行插入操作,stack2专门用来进行删除操作,当stack2内无数字时,且stack1内也没有了,返回-1;不然将stack1中的数倒置进stack2,此时stack2栈顶的元素就是先插入的数,可以实现删除头部的方法
var CQueue = function() {
this.stack1=[];
this.stack2=[];
};
/**
* @param {number} value
* @return {void}
*/
CQueue.prototype.appendTail = function(value) {
this.stack1.push(value);
return null;
};
/**
* @return {number}
*/
CQueue.prototype.deleteHead = function() {
if(this.stack2.length==0){
if(this.stack1.length==0)
{
return -1;
}
else{
while(this.stack1.length)
{
this.stack2.push(this.stack1.pop());
}
}
}
return this.stack2.pop();
};
/**
* Your CQueue object will be instantiated and called as such:
* var obj = new CQueue()
* obj.appendTail(value)
* var param_2 = obj.deleteHead()
*/
2、包含min函数的栈
- 定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是O(1)。
用stack2作为辅助栈,记录当stack1变化时,此时stack1内最小的数值。
/**
* initialize your data structure here.
*/
var MinStack = function() {
this.stack1=[];
this.stack2=[];
};
/**
* @param {number} x
* @return {void}
*/
MinStack.prototype.push = function(x) {
if(this.stack1.length==0)
{
min=x;
}else
{
min=this.stack2[this.stack2.length-1];
}
if(x<min)
{
min=x;
}
this.stack1.push(x);
this.stack2.push(min);
};
/**
* @return {void}
*/
MinStack.prototype.pop = function() {
this.stack1.pop();
this.stack2.pop();
};
/**
* @return {number}
*/
MinStack.prototype.top = function() {
return this.stack1[this.stack1.length-1];
};
/**
* @return {number}
*/
MinStack.prototype.min = function() {
return this.stack2[this.stack2.length-1];
};
/**
* 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()
*/