【LeetCode】C++ :簡單題 - 棧 232. 用棧實現佇列
阿新 • • 發佈:2021-01-06
難度簡單261
請你僅使用兩個棧實現先入先出佇列。佇列應當支援一般佇列的支援的所有操作(
push
、pop
、peek
、empty
):實現
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(雙端佇列)來模擬一個棧,只要是標準的棧操作即可。
進階:
- 你能否實現每個操作均攤時間複雜度為
O(1)
的佇列?換句話說,執行n
個操作的總時間複雜度為O(n)
,即使其中一個操作可能花費較長時間。示例:
輸入: ["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提示:
1 <= x <= 9
- 最多呼叫
100
次push
、pop
、peek
和empty
- 假設所有操作都是有效的 (例如,一個空的佇列不會呼叫
pop
或者peek
操作)通過次數75,457
開心,在上一題的啟發下,這一題寫的就順暢很多啦,大概也許是一種小小小小的進步吧,但我還是很開心的!
這種另種資料結構的互相轉換實現,很常見還是需要不斷積累的!加油!向前衝!
class MyQueue {
public:
stack<int> stin;
stack<int> stout;
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
stin.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
if(!stout.empty()){
int res = stout.top();
stout.pop();
return res;
}else{
while(!stin.empty()){
stout.push(stin.top());
stin.pop();
}
int res = stout.top();
stout.pop();
return res;
}
}
/** Get the front element. */
int peek() {
int res = this->pop();
stout.push(res);
return res;
}
/** Returns whether the queue is empty. */
bool empty() {
return stin.empty () && stout.empty();
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/