思路:
一道很簡單的題,就是棧是先進后出,隊列是先進先出,用兩個棧底相互對著,這樣一個隊列就產生了,右棧為空的情況,左棧棧底就是隊首元素,所以我們需要將左棧全部壓入右棧,右棧不為空,那么右棧就是之前壓入過,這時右棧棧頂元素就是隊首元素,大家畫畫圖應該就明白了
class MyQueue {Stack<Integer> left;Stack<Integer> right;public MyQueue() {left = new Stack<>();right = new Stack<>();}public void push(int x) {left.push(x);}public int pop() {if (right.isEmpty()) {while (!left.isEmpty()) {right.push(left.pop());}}return right.pop();}public int peek() {if (right.isEmpty()) {while (!left.isEmpty()) {right.push(left.pop());}}return right.peek();}public boolean empty() {return left.isEmpty() && right.isEmpty();}
}/*** 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();* boolean param_4 = obj.empty();*/
?