用过两个栈实现队列java

用两个栈实现队列

http://www.nowcoder.com/questionTerminal/54275ddae22f475981afa2244dd448c6

stack1只负责存,stack2只负责取
因为stack是后进先出,所以取的话必须先将stack1取出后放入stack2,此时stack1的栈顶(最后存进去的)就变为stack2的栈底,符合我们的需求
当stack2中有元素的时候,就不需要从stack1中取出放入了,什么时候stack2空了,再从stack1中取
代码如下:

/**
 * 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
 * 思路,两个stack,push的时候都往stack1中push
 * pop的时候,如果stack2无元素,则将stack1的元素pop放入stack2,然后stack2pop
 * 如果stack2有元素,则直接stack2pop
 */
public class StackQueue {

    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();

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

    public int pop() {
        if (stack1.isEmpty() && stack2.isEmpty()) {
            return -1;
        }
        if (stack2.isEmpty()) {
            while (!stack1.isEmpty()) {
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务