栈和队列----由两个栈组成队列

由两个栈组成队列

由两个栈实现一个队列,支持队列的基本操作(add poll peek),需要注意的是,stackPush向stackPop中压入数据,必须一次性的把stackPush中的元素全部压入,此外,如果stackPop不为空,不能向stackPop中压入数据。

package com.test;

import java.util.Stack;

/**
 * Created by Demrystv.
 */
public class TwoStacksQueue {
    Stack<Integer> stackPush = new Stack<Integer>();
    Stack<Integer> stackPop = new Stack<Integer>();

    public void add(int pushInt){
        stackPush.push(pushInt);
    }

    //poll是检索并删除这个队列的头
    public int poll(){
        if(stackPop.isEmpty() && stackPush.isEmpty()){
            throw new RuntimeException("Queue is empty.");
        }else if (stackPop.isEmpty()){
            while (!stackPush.isEmpty()){
                stackPop.push(stackPush.pop());
            }
        }
        return stackPop.pop();
    }

    //peek是检索但不删除这个队列的头
    public int peek(){
        if(stackPop.isEmpty() && stackPush.isEmpty()){
            throw new RuntimeException("Queue is empty.");
        }else if (stackPop.isEmpty()){
            while (!stackPush.isEmpty()){
                stackPop.push(stackPush.pop());
            }
        }
        return stackPop.peek();
    }
}
原文地址:https://www.cnblogs.com/Demrystv/p/9279974.html