首页 > 试题广场 >

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队

[问答题]
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    
    public void push(int node) {
        stack1.push(node);
    }
    
    public int pop() {
        Integer num=null;
        if(!stack2.empty()){
            num=stack2.pop();
        }
        else{
            while(!stack1.empty()){
                num=stack1.pop();
                stack2.push(num);
            }
            if(!stack2.empty())
                num=stack2.pop();
        }
        return num;
    }
}
发表于 2019-08-21 20:07:27 回复(0)