剑指offer9 用两个栈实现队列

用两个栈实现队列

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

方法1:始终在2栈取,如果空就把1栈的数据倒过去

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

    public int pop() {
        if(stack2.isEmpty()){
            while(!stack1.isEmpty()){
                stack2.add(stack1.pop());
            }
        }
        return stack2.pop();
    }
}

方法2:始终在1栈操作,每次取数据把栈的n-1个数据倒入2栈,然后操作完再倒回来

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

    public int pop() {
        while(stack1.size()>1){
            stack2.add(stack1.pop());
        }
        int res=(int)stack1.pop();
        while(!stack2.isEmpty()){
            stack1.add(stack2.pop());
        }
        return res;
    }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-11 15:08
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-10 11:27
明天又是董事长面,啥时候是个头啊
在太阳里长大的人:公司就仨人吧😂
点赞 评论 收藏
分享
今天 16:52
已编辑
门头沟学院 Java
周五投的,流程今天结束
投递地平线等公司7个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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