《剑指Offer》05用两个栈实现队列

题目:
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路:
题目很经典,也很简单,push直接push到stack1,pop的话,先将stack1中的元素弹进stack2,
从stack2中pop出一个元素,接着将stack2中的元素弹进stack1。
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 res = stack2.pop();
        while(!stack2.isEmpty()) {
            stack1.push(stack2.pop());
        }
        System.out.println(res);
        return res;
    }
}

全部评论

相关推荐

不是哥们,我投的开发岗啊,也不至于直接调剂销售岗吧
哞客37422655...:先面一面探探口风,真要转销售就得把提成问清楚;说不定还能内部跳回技术,别直接拒。
我的工作日记
点赞 评论 收藏
分享
2025-12-30 16:42
同济大学 C++
仁狂躁使者:哎呀,不用担心,我当时配环境配了两天,项目捋不清就问问导师能不能用ai,慢慢就清了,会好起来的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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