LeetCode-Implement Queue using Stacks

Bertha 。 2022-08-04 00:46 238阅读 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).

这种题可以自己先跑几个样例就会发现是有规律可循的,主要思路是两个stack,一个stack1用于push,另外一个stack2用于pop,关键就在从stack1倒到stack2的过程,还是直接上代码吧,一目了然:

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

发表评论

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

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

相关阅读