Iterator Interface in java

https://www.tutorialspoint.com/java/java_using_iterator.htm

Iterator enables you to cycle through a collection, obtaining or removing elements. ListIterator extends Iterator to allow bidirectional traversal of a list, and the modification of elements.

Thinking process I -- using built in iterator interface

  • Two iterators
  • has next => check both two iterators
  • next => check flag, and then get next
public class ZigzagIterator {
    private Iterator<Integer> it1;
    private Iterator<Integer> it2;

    private boolean isFromIt1 = true;

    public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
        it1 = v1.iterator();
        it2 = v2.iterator();
    }

    public int next() {
        if (isFromIt1 && it1.hasNext()) {
            if (it2.hasNext()) isFromIt1 = false;
            return it1.next();
        } else {
            if (it1.hasNext()) isFromIt1 = true;
            return it2.next();
        }
    }

    public boolean hasNext() {
        return it1.hasNext() || it2.hasNext();
    }
}

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

extends to k lists

https://discuss.leetcode.com/topic/26654/simple-java-solution-for-k-vector

Thinking process II -- w/o using iterator

use queue of 2d lists

public class ZigzagIterator {
    private int k;
    private List<List<Integer>> allLists;
    private int[] listIndices;
    private int nextListIndex;

    public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
        this.k = 2;
        this.allLists = new ArrayList<>();
        this.allLists.add(new ArrayList<>(v1));
        this.allLists.add(new ArrayList<>(v2));
        this.listIndices = new int[k];
        this.nextListIndex = 0;
    }

    public int next() {
        while (listIndices[nextListIndex] >= allLists.get(nextListIndex).size()) {
            nextListIndex = (nextListIndex + 1) % k;
        }

        int result = allLists.get(nextListIndex).get(listIndices[nextListIndex]);
        listIndices[nextListIndex]++;
        nextListIndex = (nextListIndex + 1) % k;
        return result;
    }

    public boolean hasNext() {
        for (int i = 0; i < k; ++i) {
            if (listIndices[i] < allLists.get(i).size()) {
                return true;
            }
        }

        return false;
    }

    private void setNext() {
        listIndices[nextListIndex] = listIndices[nextListIndex] + 1;
        if (nextListIndex + 1 >= k) {
            nextListIndex = 0;
        } else {
            nextListIndex++;
        }
    }
}

results matching ""

    No results matching ""