Design

作者: ziru_SUN | 来源:发表于2018-02-14 03:32 被阅读0次

    341. Flatten Nested List Iterator

    Stack的用法,list从后往前加入stack。
    如果涉及到移除元素的话 stack方便
    逻辑写在hasNext或者next都行
    一开始习惯写在里next里,但是总需要判断empty的情况,不如写在hasNext()方便

    public 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;
        }
    }
    

    相关文章

      网友评论

          本文标题:Design

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