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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_38158541/article/details/85225963

时间限制:1秒 空间限制:32768K 热度指数:317529

本题知识点: 队列 

题目描述

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

思路:

首先需要清楚的是,栈的特点是:先进后出;队列的特点是:先进先出

举个例子,不失一般性,PUSH1,PUSH2,PUSH3,POP,POP,PUSH4,POP,PUSH5,POP,POP,该例子队列输出的结果是12345

在此之前,我们要清楚,两个栈如何实现队列的push和pop操作,push操作与栈的push相同,直接进行即可,二pop操作,首先让push进栈1,然后栈2压入栈1的弹出,然后栈2弹出即为队列的pop,这里注意的是,因为在进行弹出后还会进行队列的继续push操作,因此,在最后要对栈1进行压入栈2的弹出,若没有这步操作,以上例子的输出结果将变为12453

import java.util.Stack;

public 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() {
        while(!stack1.isEmpty()){
            stack2.push(stack1.pop());
        }
        int popNode = stack2.pop();
        while(!stack2.isEmpty()){
            stack1.push(stack2.pop());
        }
        return popNode;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_38158541/article/details/85225963
今日推荐