232. 用棧實現(xiàn)隊列
題目:
請你僅使用兩個棧實現(xiàn)先入先出隊列厘灼。隊列應當支持一般隊列支持的所有操作(push、pop咽瓷、peek设凹、empty):
實現(xiàn) MyQueue 類:
- void push(int x) 將元素 x 推到隊列的末尾
- int pop() 從隊列的開頭移除并返回元素
- int peek() 返回隊列開頭的元素
- boolean empty() 如果隊列為空,返回 true 茅姜;否則闪朱,返回 false
說明: - 你 只能 使用標準的棧操作 —— 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
- 你所使用的語言也許不支持棧。你可以使用 list 或者 deque(雙端隊列)來模擬一個棧奋姿,只要是標準的棧操作即可锄开。
解題思路:
兩個棧,一個輸入棧胀蛮,一個輸出棧院刁。
var MyQueue = function () {
this.stackIn = [];
this.stackOut = [];
};
/**
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function (x) {
this.stackIn.push(x);
};
/**
* @return {number}
*/
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 x = this.pop();
this.stackOut.push(x);
return x;
};
/**
* @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()
*/
225. 用隊列實現(xiàn)棧
題目:
請你僅使用兩個隊列實現(xiàn)一個后入先出(LIFO)的棧,并支持普通棧的全部四種操作(push粪狼、top退腥、pop 和 empty)。
實現(xiàn) MyStack 類:
- void push(int x) 將元素 x 壓入棧頂再榄。
- int pop() 移除并返回棧頂元素狡刘。
- int top() 返回棧頂元素。
- boolean empty() 如果棧是空的困鸥,返回 true 嗅蔬;否則,返回 false 疾就。
注意: - 你只能使用隊列的基本操作 —— 也就是 push to back澜术、peek/pop from front、size 和 is empty 這些操作猬腰。
- 你所使用的語言也許不支持隊列鸟废。 你可以使用 list (列表)或者 deque(雙端隊列)來模擬一個隊列 , 只要是標準的隊列操作即可。
解題思路:
一個隊列就可以解決問題了姑荷。
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 () {
let size = this.queue.length;
size--;
while (size--) {
this.queue.push(this.queue.shift());
}
return this.queue.shift();
};
/**
* @return {number}
*/
MyStack.prototype.top = function () {
const x = this.pop();
this.queue.push(x);
return x;
};
/**
* @return {boolean}
*/
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()
*/