225. 用队列实现栈

  1. Queue<Integer> queue;
  2. /** Initialize your data structure here. */
  3. public MyStack() {
  4. queue = new LinkedList<Integer>();
  5. }
  6. /** Push element x onto stack. */
  7. public void push(int x) {
  8. int n = queue.size();
  9. queue.offer(x);
  10. for (int i = 0; i < n; i++) {
  11. queue.offer(queue.poll());///头出尾进
  12. }
  13. }
  14. /** Removes the element on top of the stack and returns that element. */
  15. public int pop() {
  16. return queue.poll();
  17. }
  18. /** Get the top element. */
  19. public int top() {
  20. return queue.peek();
  21. }
  22. /** Returns whether the stack is empty. */
  23. public boolean empty() {
  24. return queue.isEmpty();
  25. }
  26. 作者:LeetCode-Solution
  27. 链接:https://leetcode-cn.com/problems/implement-stack-using-queues/solution/yong-dui-lie-shi-xian-zhan-by-leetcode-solution/
  28. 来源:力扣(LeetCode
  29. 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。