601. 2차원 벡터를 평평하게 펴다

2415 단어
묘사
2차원 벡터의 기능을 실현하기 위해 교체기를 설계하다
예제
2차원 벡터 [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();
 */

좋은 웹페이지 즐겨찾기