美文网首页
hihocoder——栈的加强版

hihocoder——栈的加强版

作者: 掌灬纹 | 来源:发表于2019-04-13 14:15 被阅读0次

    描述
    请你实现一个加强版的栈,支持以下操作:
    push x: 向栈顶加入一个整数x
    pop: 从栈顶弹出一个整数,并且输出该整数
    inc k x: 将处于栈底的前k个整数加x。
    输入
    第一行包含一个整数N,代表操作的数量。
    以下N行每行一条操作。
    1 ≤ N ≤ 200000, 0 ≤ x ≤ 100000, 1 ≤ k ≤ 当前栈的大小
    输出
    对于每一个pop操作,输出弹出的整数数值。
    样例输入
    6
    push 1
    inc 1 2
    push 2
    inc 2 2
    pop
    pop
    样例输出
    4
    5

    个人觉得该题不适合用Java来写(TLE....),一看到题目就想用栈来实现,inc函数用栈来实现就是借助一个辅助栈,把栈中所有元素出栈进入辅助栈中,在从辅助栈中出栈把前k个数都加上x在压回原来栈中,然而在oj上一跑就超时了,虽然超时我觉得思路还是有价值的,在附上用Java的链表模拟栈的结构,读者参考一下自己区分一下吧

    import java.util.ArrayList;
    import java.util.Scanner;
    import java.util.Stack;
    
    public class  Main {
    
        static ArrayList<Integer> ans = new ArrayList<Integer>();
        static ArrayList<Integer> ans2 = new ArrayList<Integer>();
        public static void main(String[] args) {
            Stack<Integer> stack = new Stack<Integer>();
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt();
            for(int i = 0; i < n; i++) {
                String s = sc.next();
                if(s.equals("push")) {
                    int temp = sc.nextInt();
                    //push(temp, stack);
                    ans.add(0, temp);
                }
                if(s.equals("pop")) {
                    //pop(stack);
                    ans2.add(ans.get(0));
                    ans.remove(0);
                }
                if(s.equals("inc")) {
                    int k = sc.nextInt();
                    int num = sc.nextInt();
                    //inc(k, num, stack);
                    for(int j = 0; j < k; j++) {
                        ans.set(ans.size() - j - 1, 
                                ans.get(ans.size() - j - 1) + num);
                    }
                }
            }
            for (Integer e : ans2) {
                System.out.println(e);
            }
        }
    
        private static void pop(Stack<Integer> stack) {
            if(!stack.isEmpty())
                ans.add(stack.pop());
            
        }
    
        /**
         * 栈底的k个元素都加上num
         * 出栈 进新栈,在出新栈前k个元素都加num,进栈结束
         * @param k
         * @param num
         * @param stack
         */
        private static void inc(int k, int num, Stack<Integer> stack) {
            Stack<Integer> help = new Stack<Integer>();
            while(!stack.isEmpty()) {
                help.push(stack.pop());
            }
            for(int i = 0; i < k; i++) {
                stack.push(help.pop() + num);
            }
            while(!help.isEmpty()) {
                stack.push(help.pop());
            }
            
        }
    
        private static void push(int temp, Stack<Integer> stack) {
            stack.push(temp);
            
        }
    
    }
    
    

    相关文章

      网友评论

          本文标题:hihocoder——栈的加强版

          本文链接:https://www.haomeiwen.com/subject/vcwlwqtx.html