# Iterator

#### [281. Zigzag Iterator](https://leetcode.com/problems/zigzag-iterator/)

```java
public class ZigzagIterator {
    Queue<Iterator<Integer>> queue = new LinkedList<>();
    public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
        if (!v1.isEmpty()) queue.offer(v1.iterator());
        if (!v2.isEmpty()) queue.offer(v2.iterator());
    }

    public int next() {
        Iterator<Integer> curt = queue.poll();
        int val = curt.next();
        if (curt.hasNext()) queue.offer(curt);
        return val;
    }

    public boolean hasNext() {
       return !queue.isEmpty();
    }
}
```

#### [284. Peeking Iterator](https://leetcode.com/problems/peeking-iterator/)

Pre fill a peek element.

```java
class PeekingIterator implements Iterator<Integer> {
    Integer e;
    Iterator<Integer> iterator;
	public PeekingIterator(Iterator<Integer> iterator) {
	    // initialize any member here.
	    this.iterator = iterator;
        fillNext();
	}
	
  // Returns the next element in the iteration without advancing the iterator.
	public Integer peek() {
        return e;    
	}
    
  private void fillNext() {
      if (!iterator.hasNext()) {
          e = null;
      } else {
          e = iterator.next();
      }
  }
	
	// hasNext() and next() should behave the same as in the Iterator interface.
	// Override them if needed.
	@Override
	public Integer next() {
        if (e == null) return null;
	    int temp = e;
        fillNext();
        return temp;
	}
	
	@Override
	public boolean hasNext() {
	    return e != null;
	}
}
```

#### [900. RLE Iterator](https://leetcode.com/problems/rle-iterator/)

```java
class RLEIterator {
    int i = 0;
    int[] A;
    public RLEIterator(int[] A) {
        this.A = A;
    }
    
    public int next(int n) {
        while (i < A.length && n > A[i]) {
            n -= A[i];
            i += 2;
        }
        if (i >= A.length) return -1;
        A[i] -= n;
        return A[i + 1];
    }
}
```
