Sunday, June 19, 2016

Even Iterator

Question:
设计iterator, input是一个遍历1到N的iterator,你设计的iterator只返回偶数。

e.g. If N = 7, output 2, 4, 6

Code (Java):
import java.io.*;
import java.util.*;

public class Solution {
  private Iterator<Integer> it;
  Integer top = null;
  
  public Solution (Iterator<Integer> it) {
    this.it = it;
  }
  
  public boolean hasNext() {
    if (top != null) {
      return true;
    }
    
    if (!it.hasNext()) {
      return false;
    }
    
    Integer curr = it.next();
    if (curr % 2 == 0) {
      top = curr;
      return true;
    } else {
      if (!it.hasNext()) {
        return false;
      } else {
        top = it.next();
      }
    }
    
    return true;
  }
  
  public Integer next() {
    Integer result = null;
    if (top == null) {
      return null;
    } else {
      result = top;
      top = null;
    }
    
    return result;
  }
  
  public static void main(String[] args) {
    List<Integer> list = new ArrayList<>();
    int n = 7;
    for (int i = 1; i <= 10; i++) {
      list.add(i);
    }
    
    Solution sol = new Solution(list.iterator());
    
    while (sol.hasNext()) {
      System.out.println(sol.next());
    }
  }
}

No comments:

Post a Comment