Simple Java Solution using a counter


  • 0
    D
    public class ZigzagIterator {
        private Iterator <Integer> i1;
        private Iterator <Integer> i2;
        int count;
    
        public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
            i1 = v1.iterator();
            i2 = v2.iterator();
            count = 0;
        }
    
        public int next() {
            if(!hasNext()){
                return 0;
            }
            count++;
            if((count % 2 == 1 && i1.hasNext()) || (!i2.hasNext())){
                return i1.next();
            } else if((count % 2 == 0 && i2.hasNext()) || (!i1.hasNext())){
                return i2.next();
            }
            return 0;
        }
    
        public boolean hasNext() {
            return i1.hasNext() || i2.hasNext() ;
        }
    }

Log in to reply
 

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