剑指offer(5)

用两个栈实现队列

Posted by LQ on June 30, 2017

题目描述

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

思路

队列入栈是正常入栈,出栈的时候因为是先进先出,则相当于先把一个栈里的内容正常出栈到另外一个栈里,然后再按顺序出栈即可

import java.util.Stack;

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    
    public void push(int node) {
        stack1.push(new Integer(node));
    }
    
    public int pop() {
        Integer tmp=null;
    	if(!stack2.empty()){
            tmp=stack2.pop().intValue();
        }else{
            while(!stack1.empty()){
                tmp = stack1.pop();
                stack2.push(tmp);
            }
            if(!stack2.empty()){   
                tmp=stack2.pop().intValue();   
            }  
        }
        return tmp;
    }
}