【第22期】观点:IT 行业加班,到底有没有价值?

[leetcode-341]Flatten Nested List Iterator(java)

原创 2016年06月01日 09:26:15

这道题的思想是在调用hasNext的时候,将NestedInteger拆分,然后将第一个元素保存到域变量中即可。其他元素添加到链表的首部。

/**
 * // This is the interface that allows for creating nested lists.
 * // You should not implement it, or speculate about its implementation
 * public 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();
 * }
 */
public class NestedIterator implements Iterator<Integer> {
    List<NestedInteger> nestedList;
    int data;
    public NestedIterator(List<NestedInteger> nestedList) {
        this.nestedList = nestedList;
    }

    @Override
    public Integer next() {
        return data;
    }

    @Override
    public boolean hasNext() {
        while(nestedList != null && nestedList.size() > 0){
           NestedInteger tmpInt = nestedList.remove(0);
            if(tmpInt.isInteger()){
                data = tmpInt.getInteger();
                return true;
            }else{
                nestedList.addAll(0,tmpInt.getList());
            } 
        }
        return false;
    }
}

/**
 * Your NestedIterator object will be instantiated and called as such:
 * NestedIterator i = new NestedIterator(nestedList);
 * while (i.hasNext()) v[f()] = i.next();
 */
版权声明: 举报

相关文章推荐

leetcode 341. Flatten Nested List Iterator

Given a nested list of integers, implement an iterator to flatten it. Each element is either an i...

[LeetCode] Flatten Nested List Iterator

Given a nested list of integers, implement an iterator to flatten it.Each element is either an integ...

程序员升职加薪指南!还缺一个“证”!

CSDN出品,立即查看!

[leetcode] 341. Flatten Nested List Iterator 解题报告

题目链接: https://leetcode.com/problems/flatten-nested-list-iterator/ Given a nested list of integers,...

Flatten Nested List Iterator

Given a nested list of integers, implement an iterator to flatten it. Each element is either an int...

LeetCode341 Flatten Nested List Iterator(迭代器模式实践) Java

题目: Given a nested list of integers, implement an iterator to flatten it.Each element is either an ...

[Leetcode] 341. Flatten Nested List Iterator 解题报告

题目: Given a nested list of integers, implement an iterator to flatten it. Each element is ei...

[leetcode]Flatten Binary Tree to Linked List - java 先序遍历

/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * Tre...
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)