两个栈实现队列;

用两个栈实现队列

http://www.nowcoder.com/questionTerminal/54275ddae22f475981afa2244dd448c6

import java.util.Stack;

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();

    public void push(int node) {
        while(!stack2.empty()){
            Integer nodeOnWay=stack2.pop();
            stack1.push(nodeOnWay);
        }
        stack1.push(node);
        while(!stack1.empty()){
            Integer nodeOnWay=stack1.pop();
            stack2.push(nodeOnWay);
        }
    }

    public int pop() {
        if(!stack2.empty())
            return stack2.pop();
        else
            return -1;
    }
}
全部评论

相关推荐

评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务