LeetCode--Implement Stack using Queues

拼搏现实的明天。 2022-08-18 00:38 108阅读 0赞

Problem:

Implement the following operations of a stack using queues.
- push(x) – Push element x onto stack.
- pop() – Removes the element on top of the stack.
- top() – Get the top element.
- empty() – Return whether the stack is empty.
Notes:

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

Analysis:

【解法一:用两个队列,push: O(1),pop: O(n),top: O(n)】
用两个队列q1,q2实现一个栈。push时把新元素添加到q1的队尾。pop时把q1中除最后一个元素外逐个添加到q2中,然后pop掉q1中的最后一个元素,然后注意记得q1和q2,以保证我们添加元素时始终向q1中添加。top的道理类似。

【解法二:用两个队列,push: O(n),pop: O(1),top: O(1)】
所有元素都倒序保存在q1中,即后添加的元素在q1的最前端,如何做到呢?每次push时,把新元素放到空的q2,然后把q1中元素逐个添加到q2的队尾,最后交换q1和q2。这样q1队首的元素就是最后添加的元素,pop和top直接返回q1队首的元素就好。

Anwser1:

  1. class MyStack {
  2. Queue<Integer> in = new LinkedList<Integer>();
  3. Queue<Integer> out = new LinkedList<Integer>();
  4. // Push element x onto stack.
  5. public void push(int x) {
  6. in.add(x);
  7. }
  8. // Removes the element on top of the stack.
  9. public void pop() {
  10. while(in.size()>1) out.add(in.poll());
  11. in.poll();
  12. Queue<Integer> q=in;
  13. in = out;
  14. out = q;
  15. }
  16. // Get the top element.
  17. public int top() {
  18. while(in.size()>1) out.add(in.poll());
  19. int x = in.poll();
  20. out.add(x);
  21. Queue<Integer> q=in;
  22. in = out;
  23. out = q;
  24. return x;
  25. }
  26. // Return whether the stack is empty.
  27. public boolean empty() {
  28. return in.isEmpty();
  29. }
  30. }

Anwser2:

  1. class MyStack {
  2. private Queue<Integer> q1 = new LinkedList<>();
  3. private Queue<Integer> q2 = new LinkedList<>();
  4. // Push element x onto stack.
  5. public void push(int x) {
  6. q2.offer(x);
  7. while (!q1.isEmpty()) {
  8. q2.offer(q1.poll());
  9. }
  10. Queue tmp = q1;
  11. q1 = q2;
  12. q2 = tmp;
  13. }
  14. // Removes the element on top of the stack.
  15. public void pop() {
  16. q1.poll();
  17. }
  18. // Get the top element.
  19. public int top() {
  20. return q1.peek();
  21. }
  22. // Return whether the stack is empty.
  23. public boolean empty() {
  24. return q1.isEmpty();
  25. }
  26. }

发表评论

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

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

相关阅读