设计两个栈组成一个队列
import java.util.Stack;
/**
 * Created by Administrator on 17.6.2.
 */
public class TwoStacksQueue {
    public Stack<Integer> stackPush;
    public Stack<Integer> stackPop;
    public TwoStacksQueue() {
        stackPush = new Stack<Integer>();
        stackPop = new Stack<Integer>();
    }
    public void add(int num) {
        stackPush.push(num);
    }
    public int pop() {
        if (stackPush.empty() && stackPop.empty()) {
            throw new RuntimeException("empty");
        } else if (stackPop.empty()) {
            while (!stackPush.empty()) {
                stackPop.push(stackPush.pop());
            }
        }
        return stackPop.pop();
    }
    public int peek() {
        if (stackPush.empty() && stackPop.empty()) {
            throw new RuntimeException("empty");
        } else if (stackPop.empty()) {
            while (!stackPush.empty()) {
                stackPop.push(stackPush.pop());
            }
        }
        return stackPop.peek();
    }
本文标题:设计两个栈组成一个队列
本文链接:https://www.haomeiwen.com/subject/qizufxtx.html
网友评论