Implement the following operations of a queue using stacks.post
push to top
, peek/pop from top
, size
, and is empty
operations are valid.//題目描寫敘述: //使用棧實現隊列的下列操做: //push(x) --將元素x加至隊列尾部 //pop( ) --從隊列頭部移除元素 //peek( ) --獲取隊頭元素 //empty( ) --返回隊列是否爲空 //注意:你僅僅可以使用棧的標準操做,這意味着僅僅有push to top(壓棧), peek / pop from top(取棧頂 / 彈棧頂), //以及empty(推斷是否爲空)是贊成的。取決於你的語言,stack可能沒有被內建支持。你可以使用list(列表)或者deque(雙端隊列)來模擬。 //確保僅僅使用棧的標準操做就能夠,你可以假設所有的操做都是有效的(好比,不會對一個空的隊列運行pop或者peek操做) //解題方法:用兩個棧就可以模擬一個隊列,基本思路是兩次後進先出 = 先進先出, //元素入隊列老是入in棧。元素出隊列假設out棧不爲空直接彈出out棧頭元素。 //假設out棧爲空就把in棧元素出棧所有壓入out棧。再彈出out棧頭。這樣就模擬出了一個隊列。spa
//核心就是保證每個元素出棧時都通過了in,out兩個棧,這樣就實現了兩次後進先出=先進先出。 class Queue { public: stack<int> in; stack<int> out; void move(){ //將in棧內的所有元素移動到out棧 while (!in.empty()){ int x = in.top(); in.pop(); out.push(x); } } // Push element x to the back of queue. void push(int x) { in.push(x); } // Removes the element from in front of queue. void pop(void) { if (out.empty()){ move(); } if (!out.empty()){ out.pop(); } } // Get the front element. int peek(void) { if (out.empty()){ move(); } if (!out.empty()){ return out.top(); } } // Return whether the queue is empty. bool empty(void) { return in.empty() && out.empty(); } };code