Java Solution, compatible with follow up


  • 0
    M
        public class ZigzagIterator {
    	Queue<Iterator<Integer>> q;
    	public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
    		q = new LinkedList<>();
    		if (v1.size() > 0) q.offer(v1.iterator());
    		if (v2.size() > 0) q.offer(v2.iterator());
    	}
    
    	public int next() {
    		Iterator<Integer> iter = q.poll();
    		int next = iter.next();
    		if (iter.hasNext()) q.offer(iter);
    		return next;
    	}
    
    	public boolean hasNext() {
    		return q.size() > 0;
    	}
    }
    

Log in to reply
 

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