?LeetCode刷題實戰(zhàn)232:用棧實現(xiàn)隊列
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty).

示例
輸入:
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
輸出:
[null, null, null, 1, 1, false]
解釋:
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false
解題
思路: 由于隊列是先進先出的,而棧是先進后出的,所以要用2個棧來實現(xiàn)隊列的入隊出隊功能,隊列的入隊功能與棧的一樣,出隊時,先將第一個棧中的元素全部彈出,并倒入到第二個棧中,將第二個棧中棧頂元素彈出,并將stack2中剩下的元素倒回到stack1中,即實現(xiàn)一次出隊。
class MyQueue {
public:
/** Initialize your data structure here. */
stack<int> s1, s2;
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
while(!s2.empty()) {
s1.push(s2.top());
s2.pop();
}
s2.push(x);
while(!s1.empty()) {
s2.push(s1.top());
s1.pop();
}
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int a = s2.top();
s2.pop();
return a;
}
/** Get the front element. */
int peek() {
return s2.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return s2.empty();
}
};
LeetCode刷題實戰(zhàn)222:完全二叉樹的節(jié)點個數(shù)
LeetCode刷題實戰(zhàn)225:用隊列實現(xiàn)棧
LeetCode刷題實戰(zhàn)226:翻轉(zhuǎn)二叉樹
LeetCode刷題實戰(zhàn)227:基本計算器 II
LeetCode刷題實戰(zhàn)228:匯總區(qū)間
LeetCode刷題實戰(zhàn)229:求眾數(shù) II
LeetCode刷題實戰(zhàn)230:二叉搜索樹中第K小的元素
