《剑指Offer》Java语言-用两个栈实现队列

题目描述

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

思路

这个题目有几种思路。第一种,把第二个栈作为辅助空间。当push操作时,压入到第一个栈中。当要pop操作的时候,将元素从第一个栈中弹出到第二个栈中,然后出栈一个元素。然后再将元素入栈到第一个栈中。时间效率为O(N^2)第二种思路:两个栈互相作为辅助空间。入栈操作到第一个栈中,然后出栈的时候,如果第二个为空,则把第一个栈的元素出栈到第二个栈中。如果是push操作,将第二个栈的元素放到第一个中,然后再入栈。这样平均复杂度为O(N)

代码

import java.util.Stack;
    public class Solution {
        Stack<Integer> stack1 = new Stack<Integer>();
        Stack<Integer> stack2 = new Stack<Integer>();

      public  void push(int node) {
            if (stack2.empty()) {
                stack1.push(node);
            } else {
                int size = stack2.size();
                for (int i =0; i<size;i++) {
                    stack1.push(stack2.pop());
                }
                stack1.push(node);
            }
        }

        public  int pop() {
            int result = 0;
            if (stack2.empty()) {
                if (stack1.empty()) {
                    return 0;
                } else {
                    int size = stack1.size();
                    for (int i = 0; i <size; i++) {
                        stack2.push(stack1.pop());
                    }
                    result = stack2.pop();
                }
            } else {
                result = stack2.pop();
            }
            return result;
        }
    }

猜你喜欢

转载自blog.csdn.net/m0_37076574/article/details/80042381