《剑指offer》牛客网java题解-用两个栈实现队列

来源:互联网 发布:一个域名多少钱 编辑:程序博客网 时间:2024/06/10 16:42

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

这是一道比较经典的题,解法有多种,同样的还有用两个队列实现栈,leetcode上的原题。

此解法是push的时候把stack1弹向stack2,然后再从stack2弹回来。

mport java.util.Stack;public class Solution {    Stack<Integer> stack1 = new Stack<Integer>();    Stack<Integer> stack2 = new Stack<Integer>();    public void push(int node) {         while(!stack1.isEmpty())        {            stack2.push(stack1.pop());        }        stack2.push(node);        while(!stack2.isEmpty())        {            stack1.push(stack2.pop());        }    }    public int pop() {         return stack1.pop();    }}
阅读全文
0 0
原创粉丝点击