Solution URL
https://leetcode.com/submissions/detail/411981168/
代码
class MyStack {
//ans: https://leetcode-cn.com/problems/implement-stack-using-queues/solution/yong-dui-lie-shi-xian-zhan-by-leetcode-solution/
//Time: O(n) and Space: O(n) for PUSH operation, Time: O(1) and Space: O(1) for OTHER operations
Deque<Integer> q;
/** Initialize your data structure here. */
public MyStack() {
q = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
//记录当前队列大小
int n = q.size();
//压入需要存入的元素
q.push(x);
//将队首开始的n个元素pop,重新存入队尾
for(int i = 0; i < n; i++){
q.push(q.pop());
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return q.pop();
}
/** Get the top element. */
public int top() {
return q.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q.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();
*/