[LeetCode]Zigzag Iterator

public class ZigzagIterator {

    private List<Integer> v1;
    private List<Integer> v2;
    private int p1;
    private int p2;
    private boolean flg = true;
    
    public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
        this.v1 = v1;
        this.v2 = v2;
        p1 = 0;
        p2 = 0;
    }

    public int next() {
        int result = 0;
        if (p1 == v1.size() || p2 == v2.size()) {
            if (p1 != v1.size()) {
                result = v1.get(p1++);
            } else {
                result = v2.get(p2++);
            }
        } else {
            if (flg) {
                result = v1.get(p1++);
            } else {
                result = v2.get(p2++);
            }
            flg = !flg;
        }
        return result;
    }

    public boolean hasNext() {
        return p1 < v1.size() || p2 < v2.size();
    }
}

 

posted @ 2015-12-03 13:44  Weizheng_Love_Coding  阅读(119)  评论(0编辑  收藏  举报