剑指offer-7.用两个栈实现队列

https://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6?tpId=13&tqId=11158&tPage=1&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking

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

题解:
入队总在stack1中添加,出队总在stack2中弹出。
元素入队时,只需将元素push到stack1 栈顶。
元素出队时,如果stack2为空,则将stack1中的元素依次压入stack2,然后弹出stack2 栈顶元素即可。

class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();

    public void push(int node) {
        stack1.push(node);
    }

    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("the queue is empty");
        }
        if (stack2.isEmpty()) {
            while (!stack1.isEmpty()) {
                stack2.push(stack1.pop());
            }
        }

        return stack2.pop();
    }

    public boolean isEmpty() {
        if (stack1.isEmpty() && stack2.isEmpty()) {
            return true;
        } else {
            return false;
        }
    }
}

相关题目:
用两个队列实现一个桟。
这里写图片描述
出栈时,每次总是出队 queue.size()-1 个元素到另一个队列,然后再出队最后一个元素,即为最后加入的元素,即栈顶元素。
入队时,只需加入到非空的那个queue的队尾。

class Solution {
    Queue<Integer> queue1 = new LinkedList<Integer>();
    Queue<Integer> queue2 = new LinkedList<Integer>();

    public void push(int node) {
        if (queue1.isEmpty()) {
            queue2.add(node);
        } else {
            queue1.add(node);
        }
    }

    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("the stack is empty");
        }
        if (queue1.isEmpty()) {// 元素都在queue2中
            while (queue2.size() != 1) {// 将queue2中除队尾元素外都移到queue1中
                queue1.add(queue2.poll());
            }
            return queue2.poll();
        } else {// 元素都在queue1中
            while (queue1.size() != 1) {
                queue2.add(queue1.poll());
            }
            return queue1.poll();
        }
    }

    public boolean isEmpty() {
        if (queue1.isEmpty() && queue2.isEmpty()) {
            return true;
        } else {
            return false;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/zxm1306192988/article/details/80797924