[leetCode刷题笔记]341. Flatten Nested List Iterator

来源:互联网 发布:天音淘宝复制大师3.02 编辑:程序博客网 时间:2024/06/12 01:31

思路是这样的:做一个stack,然后在constructor方法中将nestedList中所有元素都添加到这个stack中(最后的元素在最底下)。hasNext方法中,如果stack空了,返回false,否则,先看栈顶元素是否为int,若不为int则getlist再将所有元素压入栈中。如果是int则退出循环

public class NestedIterator implements Iterator<Integer> {    Stack<NestedInteger> stack = new Stack();    public NestedIterator(List<NestedInteger> nestedList) {        // add element to         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;            }            else {                stack.pop();                for (int i = curr.getList().size() - 1; i >=0; i--) {                    stack.push(curr.getList().get(i));                }            }        }        return false;    }}


0 0
原创粉丝点击