zoukankan      html  css  js  c++  java
  • 341. Flatten Nested List Iterator

    /*
     * 341. Flatten Nested List Iterator
     * 2016-7-10 by Mingyang
     * 这个题目又是Iterator,这里不能直接用那个东西了
     * 而且我们知道List可以从最后一个往前遍历
     */
     class NestedIterator implements Iterator<Integer> {
        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()) {
                NestedInteger curr = stack.peek();
                if(curr.isInteger()) {
                    return true;
                }
                stack.pop();
                for(int i = curr.getList().size() - 1; i >= 0; i--) {
                    stack.push(curr.getList().get(i));
                }
            }
            return false;
        }
        @Override
        public void remove() {
            // TODO Auto-generated method stub
            
        }
    }
    interface NestedInteger {
         
        // @return true if this NestedInteger holds a single integer, rather than a nested list.
       public boolean isInteger();
    
        // @return the single integer that this NestedInteger holds, if it holds a single integer
        // Return null if this NestedInteger holds a nested list
        public Integer getInteger();
       // @return the nested list that this NestedInteger holds, if it holds a nested list
       // Return null if this NestedInteger holds a single integer
       public List<NestedInteger> getList();
    }
  • 相关阅读:
    什么是https?
    简单的理解依赖注入
    Java多线程学习笔记——信号量的使用
    算法学习之一,排序算法
    MySQL中自己不太常用的命令
    如何判断链表相交
    windows&cmd常用命令&快捷键
    ubuntu桌面安装常用软件&及常见问题
    redis在windows上安装+RedisDesktopManager
    windows php5.4,5.6,7.X添加redis扩展
  • 原文地址:https://www.cnblogs.com/zmyvszk/p/5662311.html
Copyright © 2011-2022 走看看