Pergunta de entrevista da empresa Google

Implement an Iterator of Iterators which traverses through an arbitrary number of iterators. IE, an iterator which iterates over three list iterators in the following way: L1 = a1, a2, a3 L2 = b1, b2, b3 L3 = c1, c2, c3 Then the iterator should process them in this order: a1, b1, c1, a2, b2, c2, a3, b3, c3

Respostas da entrevista

Sigiloso

22 de out. de 2017

/* * * Iterator Of Iterators Questions By Google * * */ import java.util.*; public class IteratorOfIterators implements Iterator { LinkedList list = new LinkedList(); public IteratorOfIterators(ArrayList iterator) { int i = 0; while(iterator.size() > 0) { // get each iterator Iterator current = iterator.get(i%iterator.size()); if(!current.hasNext()) { iterator.remove(current); } else list.add(current.next()); i++; } } @Override public boolean hasNext() { return !list.isEmpty(); } @Override public Integer next() { return list.removeFirst(); } public static void main(String[] args) { ArrayList list1 = new ArrayList(); ArrayList list2 = new ArrayList(); ArrayList list3 = new ArrayList(); ArrayList list4 = new ArrayList(); Integer[] arr = {1,2,3,4}; list1.addAll(Arrays.asList(arr)); list2.addAll(Arrays.asList(5,6,7,8)); list3.addAll(Arrays.asList(9,10,11,12)); list4.addAll(Arrays.asList(13,14,15,16)); Iterator it1 = list1.iterator(); Iterator it2 = list2.iterator(); Iterator it3 = list3.iterator(); Iterator it4 = list4.iterator(); ArrayList iterators = new ArrayList(); iterators.add(it1); iterators.add(it2); iterators.add(it3); iterators.add(it4); IteratorOfIterators itr = new IteratorOfIterators(iterators); while(itr.hasNext()) { System.out.println(itr.next()); } } }

Sigiloso

3 de dez. de 2017

A generic implementation supporting any number of lists and elements. A simple class of less than 20 lines of code, using a circular queue. jdoodle.com/a/fW0