Airbnb | Iterator over List of Lists

Given a list of lists, implement an iterator class to allow the client to traverse and remove elements in the list. This iterator should provide three public class member functions:

class ListIterator implements Iterator<Integer> {

	public ListIterator(List<List<Integer>> lists) {
	}

	/**
	* Return true or false if there is another element.
	*/
	public boolean hasNext();

	/**
	* Return the value of the next element.
	*/
	public Integer next();

	/**
	* Remove the last element returned by the iterator. That is, remove the element that the previous 'next()' returned.
	* This method can be called only once per call to next(), otherwise, an exception will be thrown.
	* See https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html#remove-- for details.
	*/
	public void remove();
}

The code should be well structured, and robust enough to handle any access pattern. Additionally, write code to demonstrate that the class can be used for the following basic scenarios:

  1. Print elements

    Given: [[],[1,2,3],[4,5],[],[],[6],[7,8],[],[9],[10],[]]
    Print: 1 2 3 4 5 6 7 8 9 10
  2. Remove even elements

    Given: [[],[1,2,3],[4,5],[],[],[6],[7,8],[],[9],[10],[]]
    Should result in: [[],[1,3],[5],[],[],[],[7],[],[9],[],[]]
    Print: 1 3 5 7 9
Comments (9)