栈--用两个栈实现队列(leetcode 232)

思路

使用两个栈,一个栈作为压入栈stackPush,另一个栈作为当要执行队列的peek操作和poll操作的时候的压出栈stackPop。

  • 队列offer操作:只有stackPush执行push操作
  • 队列poll操作:如果两个栈都为空抛出异常;如果stackPop为空,弹出stackPush中的元素,依次压入stackPop中,这样便实现了栈中元素的逆序;最后对stackPop执行出栈操作
  • 队列element操作:如果两个栈都为空抛出异常;如果stackPop为空,弹出stackPush中的元素,依次压入stackPop中,这样便实现了栈中元素的逆序;最后对stackPop执行peek操作
  • 空:两个栈同时为空自定义队列才为空

相当于没执行poll或element操作之前,队列中的信息完全保存在stackPush中。一旦要执行自定义队列的poll操作或者element操作(poll和element操作像是trigger一样),这时便是分岔口,需要将stackPush中的所有元素再次压入stackPop中,来实现逆序,这时自定义队列的信息完全保存在stackPop中。如果此时需要再向自定义队列中offer元素,那么只压入到stackPush栈中,不对stackPop栈做任何操作,此时两个栈加在一起是队列的全部元素。只有当stackPop中的元素都pop出去之后,再将stackPush中的元素再次push到stackPop中。如此往复。

代码

public class TwoStacksQueue {
    private Stack<Integer> stackPush;
    private Stack<Integer> stackPop;

    public TwoStacksQueue(){
        stackPop = new Stack<Integer>();
        stackPush = new Stack<Integer>();
    }

    public void offer(int x){
        stackPush.push(x);
    }

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

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

    public boolean empty(){
        return stackPop.empty()&&stackPush.empty();
    }
}
posted @ 2020-04-25 22:08  swifthao  阅读(187)  评论(0编辑  收藏  举报
Live2D