剑指Offer-用两个栈实现队列

客官°小女子只卖身不卖艺 2022-03-02 15:16 368阅读 0赞

题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

初步解题思路:使用stack1专门用来输入,stack2专门用来输出。当作为队列输出时,将stack1中的内容全部压入stack2中,然后stack2.pop()。当作为队列输入时,将stack2中的内容全部压入stack1中,然后stack1.push(value)。
最优解:初步解题思路将数据来回压入堆栈,效率较低。此时可以分段压入和输出。当stack2中没有数据时,将stack1的内容压入进行输出。当stack2中有数据时,stack1中的内容不需要移动,依旧保存在stack1中,stack1继续在原有数据上存放输入数据。

Java初步解题

  1. import java.util.Stack;
  2. public class Solution {
  3. Stack<Integer> stack1 = new Stack<Integer>();
  4. Stack<Integer> stack2 = new Stack<Integer>();
  5. public void push(int node) {
  6. while(!stack2.isEmpty()){
  7. stack1.push(stack2.pop());
  8. }
  9. stack1.push(node);
  10. }
  11. public int pop() {
  12. while(!stack1.isEmpty()){
  13. stack2.push(stack1.pop());
  14. }
  15. return stack2.pop();
  16. }
  17. }

最优解

  1. import java.util.Stack;
  2. public class Solution {
  3. Stack<Integer> stack1 = new Stack<Integer>();
  4. Stack<Integer> stack2 = new Stack<Integer>();
  5. public void push(int node) {
  6. stack1.push(node);
  7. }
  8. public int pop() {
  9. if(stack1.empty()&&stack2.empty()){
  10. throw new RuntimeException("Queue is empty!");
  11. }
  12. if(stack2.empty()){
  13. while(!stack1.empty()){
  14. stack2.push(stack1.pop());
  15. }
  16. }
  17. return stack2.pop();
  18. }
  19. }

发表评论

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

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

相关阅读