美文网首页
设计两个栈组成一个队列

设计两个栈组成一个队列

作者: hello3241 | 来源:发表于2017-06-02 21:24 被阅读0次
    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