题解 | 用两个栈实现队列

用两个栈实现队列

https://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6

import java.util.*;
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.empty()){
            int temp =stack1.pop();
            stack2.push(temp);
        }
        int r = stack2.pop();
        while(!stack2.isEmpty()){
          stack1.push(stack2.pop());
        }
        return r;
    }
}


分析一下,这个算法题使用两个栈来实现一个类似于队列的形式,对于第一个栈,作为一个中转栈,先将元素入栈,然后将元素出栈,然后再进入第二个栈,将栈顶元素输出,同时将除了栈顶元素的其他元素仍旧放到第一个栈中。

全部评论

相关推荐

LemontreeN:有的兄弟有的我今天一天面了五场,4个二面一个hr面
投递字节跳动等公司9个岗位
点赞 评论 收藏
分享
06-17 00:26
门头沟学院 Java
程序员小白条:建议换下项目,智能 AI 旅游推荐平台:https://github.com/luoye6/vue3_tourism_frontend 智能 AI 校园二手交易平台:https://github.com/luoye6/vue3_trade_frontend GPT 智能图书馆:https://github.com/luoye6/Vue_BookManageSystem 选项目要选自己能掌握的,然后最好能自己拓展的,分布式这种尽量别去写,不然你只能背八股文了,另外实习的话要多投,尤其是学历不利的情况下,多找几段实习,最好公司title大一点的
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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