Implement the following operations of a queue using stacks.
1 2 3 4
push(x) -- Push element x to the back of queue. pop() -- Removes the element from in front of queue. peek() -- Get the front element. empty() -- Return whether the queue is empty.
You must use only standard operations of a stack – which means only push to top, peek/pop from top, size, and is empty operations are valid. Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack. You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
解題思維
首先我們要先釐清柱列(Queue)與 Stack(堆)的特性,前者為先進先出,後者為後進先出,題目是要我們使用堆來實現柱列的功能,我們需要用兩個堆來完成, 一個存放資料,另一個暫存資料,解題主要思維是利用堆後進先出的特性,將儲存在第一個堆的資料,依序 pop 出來,同時 push 到暫存的堆裡,將要放入 的資料放入第一堆,最後將暫存的堆裡依序吐出到第一堆,剛好最先進去的資料排在第一個。
/** Runtime: 0 ms, faster than 100.00% of Java online submissions for Implement Queue using Stacks. Memory Usage: 40.9 MB, less than 6.25% of Java online submissions for Implement Queue using Stacks. */ import java.util.Stack;
classMyQueue{ private Stack<Integer> stack1; private Stack<Integer> stack2; /** Initialize your data structure here. */ publicMyQueue(){ stack1 = new Stack<>(); stack2 = new Stack<>(); }
/** Push element x to the back of queue. */ publicvoidpush(int x){ while(!stack1.empty()){ stack2.push(stack1.pop()); }
/** Removes the element from in front of queue and returns that element. */ publicintpop(){ return stack1.pop(); }
/** Get the front element. */ publicintpeek(){ return stack1.peek(); }
/** Returns whether the queue is empty. */ publicbooleanempty(){ return stack1.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(); * boolean param_4 = obj.empty(); */