题解 | #用两个栈实现队列#

用两个栈实现队列

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.isEmpty()){
            stack2.push(stack1.pop());
        }
        int res = stack2.pop();
        while(!stack2.isEmpty()){
            stack1.push(stack2.pop());
        }
        return res;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        String[] op = input.substring(1,input.length()-1).split(",");
        Solution solution = new Solution();
        StringBuilder builder = new StringBuilder();
        for(int i=0;i<op.length-1;i++){
            String ops = op[i];
            if(ops.contains("PSH")){
                solution.push(Integer.parseInt(ops.substring(2)));
            }
            if(ops.contains("POP")){
                builder.append(solution.pop());
                builder.append(",");
            }
        }
        if(builder.length()>0){
            System.out.println(builder.toString().substring(0,builder.length()-1));
        }
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
01-15 20:52
黑皮白袜臭脚体育生:五宿大战是吧,死去的记忆还在攻击我
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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