# 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];
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://howardyangemail.gitbook.io/decode-leetcode/array/iterator.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
