601. 摊平二维向量

描述

设计一个迭代器来实现摊平二维向量的功能

样例

给一个二维向量
[ [1,2], [3], [4,5,6] ]
通过重复调用,直到hasNext返回false,下一个返回的元素的顺序应该是:[1,2,3,4,5,6]

代码

public class Vector2D implements Iterator {
    Stack> stack = new Stack<>();
    Stack stackj;
    
    void pushListListToStack(List> vec2d) {
    Stack> temp = new Stack<>();
        for (List nested : vec2d) {
            temp.push(nested);
        }
        
        while (!temp.isEmpty()) {
            stack.push(temp.pop());
        }
    }
    
    void pushListToStack(List vec) {
    Stack temp = new Stack<>();
        for (Integer nested : vec) {
            temp.push(nested);
        }
        
        while (!temp.isEmpty()) {
            stackj.push(temp.pop());
        }
    }
    
    public Vector2D(List> vec2d) {
        pushListListToStack(vec2d);
        // Initialize your data structure here
        stackj = new Stack<>();
    }

    public Integer next() {
        // Write your code here
        if(!hasNext()) {
            return null;
        }
        return stackj.pop();
    }

    public boolean hasNext() { // 准备下一个元素
        // Write your code here
        while (stackj.isEmpty() && !stack.isEmpty())
            pushListToStack(stack.pop());
        return !stackj.isEmpty();
    }
    
    public void remove() {}
}
public class Vector2D implements Iterator {

    private Iterator> i;
    private Iterator j;

    public Vector2D(List> vec2d) {
        // Initialize your data structure here
        i = vec2d.iterator();
        j = null;
    }

    @Override
    public Integer next() {
        // Write your code here
        hasNext();
        return j.next();
    }

    @Override
    public boolean hasNext() {
        // Write your code here
        while ((j == null || !j.hasNext()) && i.hasNext())
            j = i.next().iterator();
        return j != null && j.hasNext();
    }

    @Override
    public void remove() {}
}

/**
 * Your Vector2D object will be instantiated and called as such:
 * Vector2D i = new Vector2D(vec2d);
 * while (i.hasNext()) v[f()] = i.next();
 */

你可能感兴趣的:(601. 摊平二维向量)