LeetCode232.用栈实现队列(Java实现)

链接:https://leetcode-cn.com/problems/implement-queue-using-stacks/

class MyQueue {
	
	private Stack stackA;
	private Stack stackB;
    /** Initialize your data structure here. */
    public MyQueue() {
    	stackA=new Stack();
        stackB=new Stack();
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        stackA.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        while(!stackA.isEmpty()){
        	stackB.push(stackA.pop());
        }
        int ret=stackB.pop();
        while(!stackB.isEmpty()){
        	stackA.push(stackB.pop());
        }
        return ret;
    }
    
    public int peek() {
    	while(!stackA.isEmpty()){
        	stackB.push(stackA.pop());
        }
        int ret=stackB.peek();
        while(!stackB.isEmpty()){
        	stackA.push(stackB.pop());
        }
        return ret;
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return stackA.isEmpty();
    }
}

 

你可能感兴趣的:(LeetCode编程题)