232 Implement Queue using Stacks

来源:互联网 发布:淘宝延长收货会怎样 编辑:程序博客网 时间:2024/06/05 06:40
class MyQueue {
Stack<Integer> stack = new Stack<Integer>();
Stack<Integer> tmp = new Stack<Integer>();
    // Push element x to the back of queue.
    public void push(int x) {
        stack.push(x);
    }


    // Removes the element from in front of queue.
    public void pop() {
        int size = stack.size();
        int tVal = 0;
        for(int i = 0; i < size; ++i){
        tVal = stack.peek();
        tmp.push(tVal);
        stack.pop();
        }
        tmp.pop();
        int tSize = tmp.size();
        int tmpVal = 0;
        for(int j = 0; j< tSize; ++j){
        tmpVal = tmp.peek();
        stack.push(tmpVal);
        tmp.pop();
        }
    }


    // Get the front element.
    public int peek() {
    int size = stack.size();
        int tVal = 0;
        for(int i = 0; i < size; ++i){
        tVal = stack.peek();
        tmp.push(tVal);
        stack.pop();
        }
        int res = tmp.peek();
        int tSize = tmp.size();
        int tmpVal = 0;
        for(int j = 0; j< tSize; ++j){
        tmpVal = tmp.peek();
        stack.push(tmpVal);
        tmp.pop();
        }
        return res;
    }


    // Return whether the queue is empty.
    public boolean empty() {
        if(stack.size() > 0) return false;
        else return true;
    }
}
0 0