[算法]两个栈实现一个队列

必须做到以下两点:
1.如果stackPush要往stackPop中压数据,那么必须一次性把stackPush中的数据全部压入。
2.如果stackPop不为空,stackPush绝对不能向stackPop中压入数据。

package com.darrenchan;

import java.util.Stack;

/**
 * 必须做到以下两点:
 * 1.如果stackPush要往stackPop中压数据,那么必须一次性把stackPush中的数据全部压入。
 * 2.如果stackPop不为空,stackPush绝对不能向stackPop中压入数据。
 */
public class TwoStackOneQueue {
     public static Stack<Integer> stackPush;
     public static Stack<Integer> stackPop;

    public TwoStackOneQueue(Stack<Integer> stackPush, Stack<Integer> stackPop) {
        this.stackPush = stackPush;
        this.stackPop = stackPop;
    }

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

    public static int poll(){
        if(stackPush.isEmpty() && stackPop.isEmpty()){
            throw new RuntimeException("Queue is empty!");
        }else if(stackPop.isEmpty()){
            while(!stackPush.isEmpty()){
                stackPop.push(stackPush.pop());
            }
        }
        return stackPop.pop();
    }

    public static int peek(){
        if(stackPush.isEmpty() && stackPop.isEmpty()){
            throw new RuntimeException("Queue is empty!");
        }else if(stackPop.isEmpty()){
            while(!stackPush.isEmpty()){
                stackPop.push(stackPush.pop());
            }
        }
        return stackPop.peek();
    }

    public static void main(String[] args) {
        TwoStackOneQueue queue = new TwoStackOneQueue(new Stack<Integer>(), new Stack<Integer>());
        queue.add(1);
        queue.add(2);
        queue.add(3);
        System.out.println(queue.poll());
        System.out.println(queue.peek());
        System.out.println(queue.peek());
    }
}

原文地址:https://www.cnblogs.com/DarrenChan/p/9536400.html