using two indexes


  • 0
    C
    public class ZigzagIterator {
        private List<List<Integer>> l;
        private int i, j;
    
        public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
            l = new LinkedList<List<Integer>>();
            if (!v1.isEmpty()) l.add(v1);
            if (!v2.isEmpty()) l.add(v2);
            i = j = 0;
        }
    
        public int next() {
            int res = l.get(i).get(j);
            if (j == l.get(i).size() - 1) {
                l.remove(i);
                i--;
            }
    
            if (i == l.size() - 1) {
                i=0;
                j++;
            } else {
                i++;
            }
    
            return res;
        }
    
        public boolean hasNext() {
            return !l.isEmpty();
        }
    }
    

Log in to reply
 

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