232. Implement Queue using Stacks (用栈实现队列)

浅浅的花香味﹌ 2022-07-15 01:26 265阅读 0赞

Implement the following operations of a queue using stacks.

  • push(x) — Push element x to the back of queue.
  • pop() — Removes the element from in front of queue.
  • peek() — Get the front element.
  • empty() — Return whether the queue is empty.

Notes:

  • You must use only standard operations of a stack — which means only push to top, peek/pop from top, size, and is empty operations are valid.
  • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.

  • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

    class MyQueue {

    1. private LinkedList<Integer> stack1 = new LinkedList<Integer>(),
    2. stack2 = new LinkedList<Integer>();
    3. // Push element x to the back of queue.
    4. public void push(int x) {
    5. stack1.addFirst(x);
    6. }
    7. // Removes the element from in front of queue.
    8. public void pop() {
    9. if (stack2.isEmpty()) {
    10. for (int i : stack1)
    11. stack2.addFirst(i);
    12. stack1.clear();
    13. }
    14. stack2.removeFirst();
    15. }
    16. // Get the front element.
    17. public int peek() {
    18. if (stack2.isEmpty()) {
    19. for (int i : stack1)
    20. stack2.addFirst(i);
    21. stack1.clear();
    22. }
    23. return stack2.getFirst();
    24. }
    25. // Return whether the queue is empty.
    26. public boolean empty() {
    27. return stack1.isEmpty() && stack2.isEmpty();
    28. }

    }

发表评论

表情:
评论列表 (有 0 条评论,265人围观)

还没有评论,来说两句吧...

相关阅读