(剑指offer)用两个栈来实现一个队列

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

时间限制:1秒 空间限制:32768K 热度指数:312041
本题知识点: 队列 栈

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

思路
stack1用来入队。出队的话,就把stack1依次出栈压入stack2中,再把stack2弹出一个(这个就是队头),然后再把stack2依次出栈压入stack1中,最后弹出队头。

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

猜你喜欢

转载自blog.csdn.net/ccnuacmhdu/article/details/84678732