• 设计一个集合栈


    题目描述

    请实现一种数据结构SetOfStacks,由多个栈组成,其中每个栈的大小为size,当前一个栈填满时,新建一个栈。该数据结构应支持与普通栈相同的push和pop操作。

    给定一个操作序列int[][2] ope(C++为vector<vector<int>>),每个操作的第一个数代表操作类型,若为1,则为push操作,后一个数为应push的数字;若为2,则为pop操作,后一个数无意义。请返回一个int[][](C++为vector<vector<int>>),为完成所有操作后的SetOfStacks,顺序应为从下到上,默认初始的SetOfStacks为空。保证数据合法。

    思路:用arraylist来实现栈,放进外层的arraylist里面。这个要用一个很重要的特点,就是在ans.add(temp),之后,temp.add(1),这样ans里面的temp还是会变化,因为ans里面传入的是引用不是值,所以在当前栈没有空或者没有满之前,上下文中的栈都可以使用这个引用,当发现这个stack空了,或者满了,这个时候就应该再new一个stack加到ans里面,或者去掉一个stack,还是用相同的名字来指向新的stack,进行下一补操作。

    import java.util.*;
    
    public class SetOfStacks {
        public ArrayList<ArrayList<Integer>> setOfStacks(int[][] ope, int size) {
            // write code here
            //要用arraylist来实现stack
            ArrayList<ArrayList<Integer>> ans=new ArrayList<ArrayList<Integer>>();
            ArrayList<Integer> temp=new ArrayList<Integer>();
            ans.add(temp);
            for(int i=0;i<ope.length;i++){
                if(ope[i][0]==1){//push
                    if(temp.size()<size){
                        temp.add(ope[i][1]);
                    }else{
                        temp=new ArrayList<Integer>();
                        temp.add(ope[i][1]);
                        ans.add(temp);
                    }
                }else{
                    if(temp.size()>0){
                        temp.remove(temp.size()-1);
                    }else{
                        ans.remove(ans.size()-1);
                        temp=ans.get(ans.size()-1);
                        temp.remove(temp.size()-1);
                    }
                    
                }
            }
            return ans;
        }
    }
  • 相关阅读:
    winfrom让窗体在屏幕右下角慢慢向上弹出
    winfrom的StatusStrip控件如何设置控件右对齐
    Winfrom通过Panel拖动无边框窗体
    优秀学习资源汇总
    hexo+github搭建博客跳坑
    博客园主题样式修改
    wxss无法调用本地资源图片
    微信小程序wx:for循环
    Git常用命令总结
    git push解决办法: ! [remote rejected] master -> master (pre-receive hook declined)
  • 原文地址:https://www.cnblogs.com/tobemaster/p/6158866.html
Copyright © 2020-2023  润新知