classMyQueue { Deque<Integer> q1 = newLinkedList<>(); Deque<Integer> q2 = newLinkedList<>(); /** Initialize your data structure here. */ publicMyQueue() {
} /** Push element x to the back of queue. */ publicvoidpush(int x) { q1.push(x); } /** Removes the element from in front of queue and returns that element. */ publicintpop() { if (!q2.isEmpty()) { return q2.pop(); } while(!q1.isEmpty()) { q2.push(q1.pop()); } return q2.pop(); } /** Get the front element. */ publicintpeek() { if (!q2.isEmpty()) { return q2.peek(); } while(!q1.isEmpty()) { q2.push(q1.pop()); } return q2.peek(); } /** Returns whether the queue is empty. */ publicbooleanempty() { return q1.isEmpty() && q2.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(); */