Flatten Nested List Iterator 528

Question

Given a nested list of integers, implement an iterator to flatten it.

Each element is either an integer, or a list -- whose elements may also be integers or other lists.

Example

Given the list [[1,1],2,[1,1]], By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].

Given the list [1,[4,[6]]], By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].

Solution

与Flatten List类似,但是那道题用递归的方式,而这道题要求用迭代的方式。

迭代可以利用stack来完成。先将list中所有元素从后往前压入栈中。在hasNext()中,首先判断栈是否为空,若不为空再判断栈顶元素是整数还是list,若是整数则返回true,若是list则移除栈顶元素,并将其中元素按从后往前压入栈中,并再次从头执行hasNext的步骤,直到栈为空则返回false。next则直接取出栈顶元素并返回其值(根据hasNext,一定为整数而非list)。

代码如下:

/**
 * // 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();
 * }
 */
import java.util.Iterator;

public class NestedIterator implements Iterator<Integer> {
    List<NestedInteger> list;
    Stack<NestedInteger> stack = new Stack<NestedInteger>();

    public NestedIterator(List<NestedInteger> nestedList) {
        // Initialize your data structure here.
        list = nestedList;
        for(int i = list.size() - 1; i >= 0; i--){
            stack.push(list.get(i));
        }
    }

    // @return {int} the next element in the iteration
    @Override
    public Integer next() {
        // Write your code here
        return stack.pop().getInteger();
    }

    // @return {boolean} true if the iteration has more element or false
    @Override
    public boolean hasNext() {
        // Write your code here
        while(!stack.isEmpty()){
            if(stack.peek().isInteger()){
                return true;
            }
            NestedInteger curt = stack.pop();
            for(int i = curt.getList().size() - 1; i >= 0; i--){
                stack.push(curt.getList().get(i));
            }
        }
        return false;
    }

    @Override
    public void remove() {
    }
}

/**
 * Your NestedIterator object will be instantiated and called as such:
 * NestedIterator i = new NestedIterator(nestedList);
 * while (i.hasNext()) v.add(i.next());
 */

results matching ""

    No results matching ""