使用栈实现队列的下列操作:
- push(x) -- 将一个元素放入队列的尾部。
- pop() -- 从队列首部移除元素。
- peek() -- 返回队列首部的元素。
- empty() -- 返回队列是否为空。
示例:
MyQueue queue = new MyQueue(); queue.push(1); queue.push(2); queue.peek(); // 返回 1 queue.pop(); // 返回 1 queue.empty(); // 返回 false
说明:
- 你只能使用标准的栈操作 -- 也就是只有
push to top
,peek/pop from top
,size
, 和is empty
操作是合法的。 - 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
- 假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。
思路:
在JavaScript中,栈和队列都用数组来实现,但这里只允许使用栈的操作,所以,只能使用如下操作。
a.push(x) // 把x加入栈顶
a.pop() // 出栈元素
a.length // 栈的大小
a[a.length-1] // 返回栈顶元素
对于push,栈和队列操作一样。
对于a.pop(),需要一个临时栈temp,把 a 的所有元素都 pop 并 push 进 temp,然后将temp 栈顶元素 pop,最后把temp 所有元素都 pop 并 push 进 a。
对于a.peek,和 a.pop() 类似,只是不用将 temp 栈顶元素 pop,而是保存temp[temp.length-1],并返回。
对于 a.empty,返回 a.length是否等于 0 即可。
/**
* Initialize your data structure here.
*/
var MyQueue = function() {
this.stack = [];
};
/**
* Push element x to the back of queue.
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function(x) {
this.stack.push(x);
};
/**
* Removes the element from in front of queue and returns that element.
* @return {number}
*/
MyQueue.prototype.pop = function() {
var temp = [];
for (var i = 0, size = this.stack.length; i < size; i++) {
temp.push(this.stack.pop())
}
var pop = temp.pop()
for (var j = 0, size = temp.length; j < size; j++) {
this.stack.push(temp.pop())
}
return pop;
};
/**
* Get the front element.
* @return {number}
*/
MyQueue.prototype.peek = function() {
var temp = [];
for (var i = 0, size = this.stack.length; i < size; i++) {
temp.push(this.stack.pop())
}
var peek = temp[temp.length - 1];
for (var j = 0, size = temp.length; j < size; j++) {
this.stack.push(temp.pop())
}
return peek;
};
/**
* Returns whether the queue is empty.
* @return {boolean}
*/
MyQueue.prototype.empty = function() {
return this.stack.length === 0;
};
/**
* Your MyQueue object will be instantiated and called as such:
* var obj = Object.create(MyQueue).createNew()
* obj.push(x)
* var param_2 = obj.pop()
* var param_3 = obj.peek()
* var param_4 = obj.empty()
*/