classMyStack{ private Queue<Integer> q1 = new LinkedList<>(); private Queue<Integer> q2 = new LinkedList<>(); privateint top; /** Initialize your data structure here. */ publicMyStack(){
} /** Push element x onto stack. */ publicvoidpush(int x){ q2.add(x); top = x; while (!q1.isEmpty()) { q2.add(q1.remove()); } Queue<Integer> temp = q1; q1 = q2; q2 = temp; } /** Removes the element on top of the stack and returns that element. */ publicintpop(){ q1.remove(); int res = top; if (!q1.isEmpty()) { top = q1.peek(); } return res; } /** Get the top element. */ publicinttop(){ return top; } /** Returns whether the stack is empty. */ publicbooleanempty(){ return q1.isEmpty(); } }
/** * Your MyStack object will be instantiated and called as such: * MyStack obj = new MyStack(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.top(); * boolean param_4 = obj.empty(); */
Stack<Integer> stack1 = new Stack<>(); Stack<Integer> stack2 = new Stack<>(); int top;
/** Initialize your data structure here. */ publicMyQueue(){
}
/** Push element x to the back of queue. */ publicvoidpush(int x){ if (stack1.empty()) top = x; while (!stack1.isEmpty()) stack2.push(stack1.pop()); stack2.push(x); while (!stack2.isEmpty()) stack1.push(stack2.pop());
}
/** Removes the element from in front of queue and returns that element. */ publicintpop(){ int res = stack1.pop(); if (!stack1.empty()) top = stack1.peek(); return res; }
/** Get the front element. */ publicintpeek(){ return top; }
/** Returns whether the queue is empty. */ publicbooleanempty(){ return stack1.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(); */
/** * Initialize your data structure here. */ publicMyQueue(){ stackPush = new Stack<>(); stackPop = new Stack<>(); }
/** * Push element x to the back of queue. */ publicvoidpush(int x){ stackPush.push(x); }
/** * 辅助方法:一次性将 stackPush 里的所有元素倒入 stackPop * 注意:1、该操作只在 stackPop 里为空的时候才操作,否则会破坏出队入队的顺序 * 2、在 peek 和 pop 操作之前调用该方法 */ privatevoidshift(){ if (stackPop.isEmpty()) { while (!stackPush.isEmpty()) { stackPop.push(stackPush.pop()); } } }
/** * Removes the element from in front of queue and returns that element. */ publicintpop(){ shift(); if (!stackPop.isEmpty()) { return stackPop.pop(); } thrownew RuntimeException("队列里没有元素"); }
/** * Get the front element. */ publicintpeek(){ shift(); if (!stackPop.isEmpty()) { return stackPop.peek(); } thrownew RuntimeException("队列里没有元素"); }
/** * Returns whether the queue is empty. */ publicbooleanempty(){ return stackPush.isEmpty() && stackPop.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(); */