341. Flatten Nested List Iterator

A question before this is the Nested List Weight Sum, and it requires recursion to solve. As it carries to this problem that we will need recursion to solve it. But since we need to access each NestedInteger at a time, we will use a stack to help.

这题我做的时候就觉得要是能用递归就好了,但是由于一次只能next()取一个,所以不知咋办了。看了一眼solutions,用了stack,然后去健身了,健身的时候想到了,就是把get到的东西不停的往stack里push,刚才自己试着实现了一下,代码基本跟答案一致,但是我一开始想的是把hasNext里面的操作放到next()里面,但是那样有个问题,如果是[[]]这种情况,我最终返回了一个null,它结果是[null],而需要的是[]。

所以,堆栈操作要放在hashNext里。

    Stack<NestedInteger> stack = new Stack<>();

    public NestedIterator(List<NestedInteger> nestedList) {
        for (int i = nestedList.size() - 1; i >= 0; i--) {
            stack.push(nestedList.get(i));
        }
    }

    @Override
    public Integer next() {
        return stack.pop().getInteger();
    }

    @Override
    public boolean hasNext() {
        while (!stack.isEmpty()) {
            //不可以直接pop
            NestedInteger ni = stack.peek();
            if (ni.isInteger()) {
                return true;
            }
            stack.pop();
            List<NestedInteger> list = ni.getList();
            for (int i = list.size() - 1; i >= 0; i--) {
                stack.push(list.get(i));
            }
        }
        return false;
    }

有空做一下Nested List Weight Sum这题。
今天要熬夜做ppt。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,776评论 0 33
  • 父爱,是一座山 深沉、坚韧、博爱, 父爱,是一片海 浓郁、包容、深远 父爱,是一盏灯 指引、奉献、温暖 父爱,是一...
    货车司机牛二哥阅读 299评论 1 4
  • 三年攻关,一朝得成。自红羽大将被暗杀之后两国军中又有几名将军被暗杀,其余将令听闻纷纷色变,能撤则撤。众军无人带领,...
    淳于恒阅读 339评论 0 0
  • 我是农村出来的,一直以来就是胆小、懦弱、怕事。直到现在,我才在和35mm君的聊天中明白:自己能走出去,也才能让别人...
    东田南阅读 250评论 2 0