嘔嘔嘔
當 Pycon 志工還要寫這個真D累
所以我要偷懶一下 ;)
沒錯,直接延續昨天內容,但今天來複製貼上一下:用 stack 做 queue 吧!
class MyQueue {
stack<int> input, output;
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
input.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
peek();
return output.top();
}
/** Get the front element. */
int peek() {
if (output.empty())
while (input.size())
output.push(input.top()), input.pop();
return output.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return input.empty() && output.empty();
}
};
這一題也是前兩天提到演算法聖經裡有的一題呢!
Show how to implement a stack using two queues. Analyze the running time of the stack operations.