JZ5 用两个栈实现队列

用两个栈实现队列

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) {
        stack1.push(node);
    }

    public int pop() {
        while(!stack1.isEmpty()) stack2.push(stack1.pop());
        int t=stack2.pop();
        while(!stack2.isEmpty()) stack1.push(stack2.pop());
        return t;
    }
}

解法二:优化

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(node);
    }

    public int pop() {
        if(!stack2.isEmpty())
            return stack2.pop();
        while(!stack1.isEmpty()) stack2.push(stack1.pop());
        return stack2.pop();        
    }
}
全部评论

相关推荐

阿武同学:基本信息保留前面三行,其他的可以全部删掉,邮箱最重要的你没写,主修课程精简到8个以内,实习里面2/3/4都是水内容的,非要写的话建议两到三句话,项目经历排版优化下,自我评价缩到三行
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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