题一:用栈实现队列
地址:https://leetcode-cn.com/problems/implement-queue-using-stacks/,题号:232。
【解题思路】
首先我们知道,栈是先入后出,队列是先入先出的,所以一个栈肯定是实现不了这个功能,这里我们使用了两个栈。一个输入栈,所有的push操作都要先push到这个栈中;另一个是输出栈,所有的输出都从输出栈中弹出。
这里需要提示一下的是,一开始输出栈没有内容,必须要先把输入栈中所有的元素都移到输出栈中,然后调用pop或者peek时才能从输出栈中输出,而输出栈也必须先把元素都输出完了才能再次从输出栈中移动元素。
// initializevar MyQueue = function() {this.inputStack = [];this.ouputStatck = [];};// pushMyQueue.prototype.push = function(x) {this.inputStack.push(x);};// popMyQueue.prototype.pop = function() {if(!this.ouputStatck.length) { // 先要判断输出栈没有元素while(this.inputStack.length>0) { // 然后再从输入栈挪元素,挪要全部挪完this.ouputStatck.push(this.inputStack.pop());}}return this.ouputStatck.pop();};// peekMyQueue.prototype.peek = function() {if(!this.ouputStatck.length) {while(this.inputStack.length>0) {this.ouputStatck.push(this.inputStack.pop());}}return this.ouputStatck[this.ouputStatck.length-1];};// emptyMyQueue.prototype.empty = function() {if(this.inputStack.length || this.ouputStatck.length) {return false;} else {return true;}};
题二:用队列实现栈
地址:https://leetcode-cn.com/problems/implement-stack-using-queues/,题号:225。
【解题思路】
这个例子的思路更简单,具体过程不再赘述,自行查看代码。
var MyStack = function() {this.queue = [];};MyStack.prototype.push = function(x) {this.queue.push(x);};MyStack.prototype.pop = function() {return this.queue.pop();// 也可以不用apilet last = this.queue[this.queue.length-1];this.queue.length--;return last;};MyStack.prototype.top = function() {return this.queue[this.queue.length-1];};MyStack.prototype.empty = function() {return this.queue.length === 0;};
to be continue…
