Simple Java based on Iterator interface


  • 0
    J
    public class ZigzagIterator {
    private List<Iterator<Integer>> iterators;
    private int index;
    
    public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
    	iterators = new ArrayList<>();
    	iterators.add(v1.iterator());
    	iterators.add(v2.iterator());
    	index = 0;
    }
    public int next() {
    	Integer n;
        if (iterators.get(index).hasNext()) {
        	n = iterators.get(index).next();
        	index = (index + 1) % 2;
        } else {
        	index = (index + 1) % 2;
        	n = iterators.get(index).next();
        }
        return n;
    }
    
    public boolean hasNext() {
        return iterators.get(0).hasNext() || iterators.get(1).hasNext();
    } }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.