https://leetcode-cn.com/problems/implement-stack-using-queues/

    1. class MyStack {
    2. Queue<Integer> queue;
    3. public MyStack() {
    4. queue = new LinkedList<>();
    5. }
    6. public void push(int x) {
    7. // 1. 首先记录当前队列长度
    8. int size = queue.size();
    9. // 2. 把 x 入队
    10. queue.offer(x);
    11. // 3. Q 中原先所有的元素先出队,然后再入队
    12. for (int i = 0; i < size; i++) {
    13. queue.offer(queue.poll());
    14. }
    15. }
    16. public int pop() {
    17. return queue.poll();
    18. }
    19. public int top() {
    20. return queue.peek();
    21. }
    22. public boolean empty() {
    23. return queue.isEmpty();
    24. }
    25. }
    26. /**
    27. * Your MyStack object will be instantiated and called as such:
    28. * MyStack obj = new MyStack();
    29. * obj.push(x);
    30. * int param_2 = obj.pop();
    31. * int param_3 = obj.top();
    32. * boolean param_4 = obj.empty();
    33. */