用两个栈实现队列_剑指offer

 

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

 

    Stack stack1 = new Stack();
    Stack stack2 = new Stack();

    public void push(int node) {
        stack1.push(node);
    }
    
    public int pop() {
    	stack2.clear();
    	while(!stack1.isEmpty()) {
    		//堆栈1出栈到堆栈2中
    		stack2.push(stack1.pop());
    	}
    	int result = stack2.pop();
    	while(stack2.isEmpty()) {
    		stack1.push(stack2.pop());
    	}
    	return result;
    }

 

你可能感兴趣的:(剑指Offer)