題目描述
使用隊列實現棧的下列操作:
push(x) -- 元素 x 入棧
pop() -- 移除棧頂元素
top() -- 獲取棧頂元素
empty() -- 返回棧是否爲空
注意:
你只能使用隊列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 這些操作是合法的。
你所使用的語言也許不支持隊列。 你可以使用 list 或者 deque(雙端隊列)來模擬一個隊列 , 只要是標準的隊列操作即可。
你可以假設所有操作都是有效的(例如, 對一個空的棧不會調用 pop 或者 top 操作)。
解題思路
假裝queue是一個隊列,將元素入隊列後,則這個元素則是一個棧頂元素,但在隊列中他是一個最後出隊列的元素。所以我們需要將它前面的元素,依次出隊列在入隊列,這樣當前元素即成了隊列的首元素(即模擬棧的棧頂元素)。
/**
* Initialize your data structure here.
*/
var MyStack = function() {
this.queue = []
};
/**
* Push element x onto stack.
* @param {number} x
* @return {void}
*/
MyStack.prototype.push = function(x) {
let size = this.queue.length
this.queue.push(x)
for (let i = 0; i < size; i++)
this.queue.push(this.queue.shift())
};
/**
* Removes the element on top of the stack and returns that element.
* @return {number}
*/
MyStack.prototype.pop = function() {
return this.queue.shift()
};
/**
* Get the top element.
* @return {number}
*/
MyStack.prototype.top = function() {
return this.queue[0]
};
/**
* Returns whether the stack is empty.
* @return {boolean}
*/
MyStack.prototype.empty = function() {
return this.queue.length === 0
};
/**
* 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()
*/
題目來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/implement-stack-using-queues