用两个堆栈实现队列
var MyQueue = function() {
//写入栈
this.stackIn = [];
//弹出栈
this.stackOut = [];
};
/**
* @param {number} x
* @return {void}
*/
//写入栈顶,与队列在尾部增强元素规则一样,直接push
MyQueue.prototype.push = function(x) {
this.stackIn.push(x)
};
/**
* @return {number}
*/
//弹出操作,需要两次入栈出栈,一次入栈是LIFO,两次入栈就是FIFO
MyQueue.prototype.pop = function() {
const size = this.stackOut.length;
if(size) {
return this.stackOut.pop();
}
while(this.stackIn.length) {
this.stackOut.push(this.stackIn.pop());
}
return this.stackOut.pop();
};
/**
* @return {number}
*/
//返回队头元素,实际上就是弹出栈的栈顶
MyQueue.prototype.peek = function() {
const result = this.pop();
this.stackOut.push(result);
return this.stackOut[this.stackOut.length - 1];
};
/**
* @return {boolean}
*/
MyQueue.prototype.empty = function() {
return !this.stackIn.length && !this.stackOut.length
};
/**
* Your MyQueue object will be instantiated and called as such:
* var obj = new MyQueue()
* obj.push(x)
* var param_2 = obj.pop()
* var param_3 = obj.peek()
* var param_4 = obj.empty()
*/
- 队列是队头(front)出数据(pop),队尾(end)进数据(push),可对比日常生活中的排队。在计算机中常见的例子比如打印队列,就是先进先处理。
- 堆栈是进栈和出栈全在一端操作,即栈顶。是一种先进后出的数据结构。主要应用包括在编译器和内存中保存变量、方法调用等,也被用于浏览器和其他应用的历史记录(返回按钮)。
- 用堆栈实现队列,写入操作是一样的,直接push。但是pop和peek需要两个堆栈,首先将待写数据写入输入堆栈,此时如果直接出栈,那么是FILO。但是如果加一个弹出栈来接受写入栈弹出的元素,那么元素再从弹出栈进行pop操作的时候,相当于2次倒序,那么就符合队列从头部弹出数据的要求了(2*FILO = FIFO).
用单个队列实现堆栈
var MyStack = function() {
this.queue = [];
};
/**
* @param {number} x
* @return {void}
*/
//写入规则一样,栈顶即队尾
MyStack.prototype.push = function(x) {
this.queue.push(x);
};
/**
* @return {number}
*/
//弹出栈顶元素,就是队尾
MyStack.prototype.pop = function() {
if(this.queue.length !== null) {
let result = this.queue[this.queue.length - 1];
this.queue.pop();
return result;
}
};
/**
* @return {number}
*/
//返回队尾元素
MyStack.prototype.top = function() {
return this.queue[this.queue.length - 1];
};
/**
* @return {boolean}
*/
//length为0即为空
MyStack.prototype.empty = function() {
return !this.queue.length
};
/**
* Your MyStack object will be instantiated and called as such:
* var obj = new MyStack()
* obj.push(x)
* var param_2 = obj.pop()
* var param_3 = obj.top()
* var param_4 = obj.empty()
*/
心得体会
坚持就是胜利!耶!每一天都元气满满!